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.
Help ▸ Export Diagnostics, and a log of what each tab's page did (#60)
Victor Kildahl1994323ae4a1
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swiftindex 3e3cc4a..6467c35 100644--- a/Sources/Cra/App/AppDelegate.swift+++ b/Sources/Cra/App/AppDelegate.swift@@ -534,6 +534,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {return}if let id = dict["extensionAction"] { main.runExtensionAction(id); return }+ if let path = dict["exportDiagnostics"] {+ Diagnostics.export(windows: mainWindows, store: store, to: URL(fileURLWithPath: path))+ return+ }if let f = dict["floatingSidebar"] { if f == "1" { main.floatingSidebar?.show() } else { main.floatingSidebar?.hide(animated: true) }; return }if let method = dict["bcdp"] {CraCEFRuntime.sendBrowserDevToolsMethod(method, params: dict["params"] ?? "{}") { result, error in@@ -999,6 +1003,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {link.representedObject = urlhelp.addItem(link)}+ help.addItem(.separator())+ help.addItem(withTitle: "Export Diagnostics…", action: #selector(exportDiagnostics), keyEquivalent: "").target = selfmenubar.addItem(submenu: help, title: "Help")NSApp.helpMenu = help@@ -1013,6 +1019,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {main.showWindow(nil)}+ /// A zip of logs and page state for a bug report (Diagnostics.swift).+ @objc private func exportDiagnostics() {+ Diagnostics.export(windows: mainWindows, store: store)+ }+@objc private func showAbout() {let info = Bundle.main.infoDictionarylet version = info?["CFBundleShortVersionString"] as? String ?? ""diff --git a/Sources/Cra/App/main.swift b/Sources/Cra/App/main.swiftindex c81a0a4..faa79c5 100644--- a/Sources/Cra/App/main.swift+++ b/Sources/Cra/App/main.swift@@ -21,6 +21,7 @@ MainActor.assumeIsolated {// The run loop has not started, so the list can still hold a Cra that just quit.let me = ProcessInfo.processInfo.processIdentifierlet profileIsFree = !NSRunningApplication.runningApplications(withBundleIdentifier: Bundle.main.bundleIdentifier ?? "").contains(where: { $0.processIdentifier != me && kill($0.processIdentifier, 0) == 0 })+ CraLog.startSession(owner: profileIsFree)// Cookies and passwords move from the mock keychain to Cra's Keychain item first,// staged imports included, so everything below writes with the key Chromium reads.SafeStorage.prepare(profileIsFree: profileIsFree)@@ -61,6 +62,9 @@ MainActor.assumeIsolated {DispatchQueue.main.async { delegate.bootstrapIfNeeded() }HitchMonitor.startIfRequested()CraCEFRuntime.runMessageLoop()+ // A log that ends without this line ended in a crash or a forced quit.+ CraLog.note("Cra quits")+ CraLog.flush()delegate.applicationWillShutdown()CraCEFRuntime.shutdown()}diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swiftindex 5745ab5..a0b7f02 100644--- a/Sources/Cra/Services/BrowserManager.swift+++ b/Sources/Cra/Services/BrowserManager.swift@@ -101,9 +101,10 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {if let rt = takeRuntimeFromOtherWindow?(tabID) {rt.browser.delegate = selfadd(rt)- if inRightProfile(rt) { return rt }+ if inRightProfile(rt) { log(tabID, "moves its page in from another window"); return rt }release(tabID)?.browser.close()}+ log(tabID, "opens a page for \(site(tab.url, tabID))")let browser = CraBrowser(frame: container.bounds, url: tab.url, delegate: self, incognito: store.isIncognito(item: tabID),profilePath: store.profilePath(item: tabID))return register(browser: browser, tabID: tabID)@@ -117,6 +118,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {browser.containerView.removeFromSuperview()browser.delegate = selflet rt = register(browser: browser, tabID: tabID)+ log(tabID, "takes over a Little Window's page")store.updateTab(tabID, url: browser.currentURL, title: browser.currentTitle)return rt}@@ -222,11 +224,41 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {visibleTabID = focused.flatMap { newSet.contains($0) ? $0 : nil } ?? shown.firstif wasVisible != Set(shown) { HitchMonitor.mark("page-shown") }if focus, let f = visibleTabID, let rt = runtimes[f] { rt.browser.setFocused(true) }- for id in shown where !wasVisible.contains(id) { scheduleSnapshot(id) }+ for id in shown where !wasVisible.contains(id) {+ scheduleSnapshot(id)+ if let rt = runtimes[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)+ }+ }syncDevToolsVisibility()delegate?.browserManagerPageWindowsChanged(focus: focus)}+ // MARK: Diagnostics++ /// Tab ids are cut to 8 characters, enough to follow one tab through the log.+ private func log(_ id: UUID, _ message: String) { CraLog.note("tab \(id.uuidString.prefix(8)) \(message)") }++ /// The page's own profile when there is one: an incognito tab can leave the store before a late line.+ private func site(_ url: String, _ id: UUID, _ browser: CraBrowser? = nil) -> String {+ 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) }+ 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))")+ }+ }+ }+// MARK: Tab switcher thumbnails/// Chromium renders nothing for a hidden page, so thumbnails are taken while a tab is@@ -285,6 +317,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {// CEF closes asynchronously. Retire ownership first so reopening the tab// creates a new browser, and late callbacks cannot mutate its replacement.guard let rt = release(tabID) else { return }+ log(tabID, "closes its page")rt.browser.containerView.isHidden = trueclosingBrowsers[ObjectIdentifier(rt.browser)] = rt.browserrt.browser.close()@@ -320,8 +353,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {let refusal = Self.sleepRefusal(result)guard refusal.isEmpty else { return self.keepAwake(rt, url, refusal) }if !rt.browser.isIncognito {- NSLog("Cra: tab sleep unloads %@ (hidden %d min)", Self.logHost(url),- Int(Date().timeIntervalSince(rt.hiddenAt ?? Date()) / 60))+ CraLog.note("tab sleep unloads \(CraLog.host(url)) (hidden \(Int(Date().timeIntervalSince(rt.hiddenAt ?? Date()) / 60)) min)")}self.unload(id)}@@ -338,17 +370,12 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {/// Asked again after the back-off; the log names the site once per reason (never an incognito one).private func keepAwake(_ rt: TabRuntime, _ url: String, _ refusal: String) {rt.sleepProbeAfter = Date().addingTimeInterval(Self.refusalBackoff)- if rt.sleepRefusal != refusal, !rt.browser.isIncognito { NSLog("Cra: tab sleep keeps %@ awake: %@", Self.logHost(url), refusal) }+ if rt.sleepRefusal != refusal, !rt.browser.isIncognito { CraLog.note("tab sleep keeps \(CraLog.host(url)) awake: \(refusal)") }rt.sleepRefusal = refusal}static let refusalBackoff: TimeInterval = 10 * 60- /// Only the host: logs get shared in bug reports.- private static func logHost(_ url: String) -> String {- URL(string: url).flatMap { $0.host ?? $0.scheme.map { "\($0):" } } ?? "(no page)"- }-private func canSleep(_ rt: TabRuntime, before cutoff: Date) -> Bool {let b = rt.browserreturn rt.hiddenAt.map { $0 < cutoff } == true && !visibleTabIDs.contains(rt.tabID)@@ -608,7 +635,9 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {}func browser(_ browser: CraBrowser, didFinishLoadingURL url: String, title: String, statusCode: Int) {- guard let id = tabID(of: browser), !browser.isIncognito else { return }+ guard let id = tabID(of: browser) else { return }+ log(id, "loaded \(site(url, id, browser)) (HTTP \(statusCode))")+ guard !browser.isIncognito else { return }store.recordVisit(url: url, title: title.isEmpty ? (store.item(id)?.tab?.savedTitle ?? "") : title)}@@ -789,6 +818,6 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {delegate?.browserManagerDidUpdate(id)delegate?.browserManagerPageWindowsChanged(focus: false)// window.close() (a sign-in or payment popup finishing): the tab goes, like Chrome.- if browser.closedByPage { delegate?.browserManagerPageClosedTab(id) }+ if browser.closedByPage { log(id, "closed by its page"); delegate?.browserManagerPageClosedTab(id) }}}diff --git a/Sources/Cra/Services/Diagnostics.swift b/Sources/Cra/Services/Diagnostics.swiftnew file mode 100644index 0000000..3eabb74--- /dev/null+++ b/Sources/Cra/Services/Diagnostics.swift@@ -0,0 +1,298 @@+import AppKit+import CraCEF+import UniformTypeIdentifiers++/// Cra's own log, `cra.log` next to Chromium's: what Cra did with each page (opened, shown,+/// loaded, closed) and what the page looked like a moment after it was shown, so a report of+/// a tab that "stays white" can be traced without a debugger. Lines name sites by host only,+/// never the full address: the log is meant to be sent (Help ▸ Export Diagnostics…).+enum CraLog {+ private static let queue = DispatchQueue(label: "dk.kildahl.cra.log", qos: .utility)+ nonisolated(unsafe) private static var handle: FileHandle?+ nonisolated(unsafe) private static var written = 0+ /// A runaway loop must not fill the disk; a session's log is a few hundred kB.+ private static let limit = 8 << 20++ static var file: URL { AppPaths.file("cra.log") }+ static var previousFile: URL { AppPaths.file("cra.previous.log") }+ static var chromiumPreviousFile: URL { AppPaths.file("chromium.previous.log") }++ /// Before Chromium starts. Only the Cra that owns the data folder rotates: a second launch+ /// that hands its URLs to the running one and quits would move that one's logs away.+ static func startSession(owner: Bool) {+ let fm = FileManager.default+ if owner {+ for (current, previous) in [(file, previousFile), (AppPaths.log, chromiumPreviousFile)] where fm.fileExists(atPath: current.path) {+ try? fm.removeItem(at: previous)+ try? fm.moveItem(at: current, to: previous)+ }+ }+ // Above 10: Chromium's DevTools pipe needs descriptors 3 and 4 free (CraCDPPipeSetUp),+ // and this file is opened before Chromium starts.+ let fd = open(file.path, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0o644)+ if fd >= 0 {+ let high = fcntl(fd, F_DUPFD_CLOEXEC, 10)+ close(fd)+ if high >= 0 { handle = FileHandle(fileDescriptor: high, closeOnDealloc: true) }+ }+ let info = Bundle.main.infoDictionary+ note("Cra \(info?["CFBundleShortVersionString"] as? String ?? "?") (\(info?["CFBundleVersion"] as? String ?? "?")) starts, pid \(getpid())\(owner ? "" : ", another Cra owns the data folder")")+ }++ static func note(_ message: String) {+ NSLog("Cra: %@", message)+ let line = "\(timestamp.string(from: Date())) \(message)\n"+ queue.async {+ guard let handle, written < limit, let data = line.data(using: .utf8) else { return }+ written += data.count+ try? handle.write(contentsOf: data)+ }+ }++ /// Waits for lines still being written (before the log is copied).+ static func flush() { queue.sync {} }++ private static let timestamp: DateFormatter = {+ let f = DateFormatter()+ f.locale = Locale(identifier: "en_US_POSIX")+ f.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"+ return f+ }()++ /// Only the host: logs get shared in bug reports.+ static func host(_ url: String) -> String {+ URL(string: url).flatMap { $0.host ?? $0.scheme.map { "\($0):" } } ?? "(no page)"+ }+}++/// What a page holds, asked from the page itself: a blank tab tells apart a navigation that+/// never committed (about:blank), a page Chromium thinks is hidden, one that has content but+/// never painted it, and one that is simply empty.+@MainActor+enum PageProbe {+ private static let script = """+ JSON.stringify({blank: location.href === 'about:blank', ready: document.readyState, visibility: document.visibilityState,+ viewport: innerWidth + 'x' + innerHeight + '@' + devicePixelRatio,+ scrollHeight: document.documentElement ? document.documentElement.scrollHeight : 0,+ elements: document.getElementsByTagName('*').length,+ text: document.body ? document.body.textContent.length : -1,+ painted: performance.getEntriesByName('first-contentful-paint').length > 0})+ """++ /// One line ("ready=complete visibility=visible …"), or why there is none.+ static func run(_ browser: CraBrowser, completion: @escaping (String) -> Void) {+ guard browser.isCreated, !browser.isClosed else { completion("no browser yet"); return }+ let body = try? JSONSerialization.data(withJSONObject: ["expression": script, "returnByValue": true])+ var answered = false+ let finish: (String) -> Void = { line in+ guard !answered else { return }+ answered = true+ completion(line)+ }+ // A hung renderer never answers; that is an answer too.+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) { finish("no answer in 3 s (renderer busy or gone)") }+ browser.sendDevToolsMethod("Runtime.evaluate", params: body.flatMap { String(data: $0, encoding: .utf8) } ?? "{}") { result, error in+ DispatchQueue.main.async {+ guard let data = result?.data(using: .utf8),+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let value = (json["result"] as? [String: Any])?["value"] as? String,+ let fields = (try? JSONSerialization.jsonObject(with: Data(value.utf8))) as? [String: Any] else {+ finish("probe failed: \(error ?? "no result")")+ return+ }+ finish(["blank", "ready", "visibility", "viewport", "scrollHeight", "elements", "text", "painted"]+ .map { "\($0)=\(fields[$0].map { "\($0)" } ?? "?")" }.joined(separator: " "))+ }+ }+ }++ /// Where Cra put the page: its view's size and whether anything hides it.+ static func viewState(_ rt: TabRuntime) -> String {+ var views = [rt.browser.containerView]+ if let host = rt.hostWindow {+ views = EmbeddedPages.pageViews(of: host) ?? [host.contentView].compactMap { $0 }+ }+ let shown = views.map { v -> String in+ let hidden = sequence(first: v, next: \.superview).contains { $0.isHidden }+ return "\(Int(v.frame.width))x\(Int(v.frame.height))\(hidden ? " hidden" : "")\(v.window == nil ? " no-window" : "")"+ }+ var s = "view=\(shown.joined(separator: ","))"+ if let host = rt.hostWindow {+ s += " pageWindow=\(host.isVisible ? "visible" : "not visible")\(EmbeddedPages.isHost(host) ? " embedded" : "") alpha=\(host.alphaValue)"+ }+ // Chromium reports a page in a covered window as hidden (visibility=hidden), which is+ // fine; hidden in a window on screen is not.+ if let w = views.first?.window {+ s += " window=\(w.occlusionState.contains(.visible) ? "on screen" : "covered")\(NSApp.isActive ? "" : " app=inactive")"+ }+ return s+ }+}++/// Help ▸ Export Diagnostics…: a zip a user can attach to an issue or send by mail. Holds+/// Cra's and Chromium's logs (this launch and the last), the on-screen pages' state, the GPU+/// report and recent crash reports. Addresses are cut to their host and the home folder to+/// `~`; no history, cookies, passwords or page content leave the Mac.+@MainActor+enum Diagnostics {+ /// Asks where to save, unless `destination` is given (cra://debug?exportDiagnostics=<path>).+ static func export(windows: [MainWindowController], store: SidebarStore, to destination: URL? = nil) {+ CraLog.note("diagnostics export started")+ collectPages(windows: windows, store: store) { pages in+ CraCEFRuntime.sendBrowserDevToolsMethod("SystemInfo.getInfo", params: "{}") { gpu, error in+ DispatchQueue.main.async {+ save(pages: pages, gpu: gpu ?? "{\"error\": \"\(error ?? "no answer")\"}", store: store, to: destination)+ }+ }+ }+ }++ private static func collectPages(windows: [MainWindowController], store: SidebarStore, completion: @escaping (String) -> Void) {+ var sections: [String] = []+ var pending: [(String, CraBrowser)] = []+ for (n, w) in windows.enumerated() {+ let m = w.browsers!+ var s = "Window \(n + 1)\(w.window?.isKeyWindow == true ? " (key)" : ""): \(m.runtimes.count) live pages, frame \(w.window.map { NSStringFromRect($0.frame) } ?? "-")\n"+ for id in m.visibleTabIDs {+ let item = store.item(id)+ let incognito = store.isIncognito(item: id)+ let saved = incognito ? "(incognito)" : item?.tab.map { CraLog.host($0.url) } ?? "(no tab)"+ guard let rt = m.runtime(for: id) else { s += " on screen \(id.uuidString.prefix(8)): \(saved), no page\n"; continue }+ let page = incognito ? "(incognito)" : CraLog.host(rt.browser.currentURL)+ s += " on screen \(id.uuidString.prefix(8)): sidebar \(saved), page \(page), loading=\(rt.browser.isLoading) \(PageProbe.viewState(rt))\n"+ if !incognito { pending.append((" probe \(id.uuidString.prefix(8)): ", rt.browser)) }+ }+ s += "\n" + w.embeddedPagesDump()+ sections.append(s)+ }+ var probes: [String] = Array(repeating: "", count: pending.count)+ let group = DispatchGroup()+ for (i, (label, browser)) in pending.enumerated() {+ group.enter()+ PageProbe.run(browser) { probes[i] = label + $0; group.leave() }+ }+ group.notify(queue: .main) {+ completion(sections.joined(separator: "\n") + "\n" + probes.joined(separator: "\n") + "\n")+ }+ }++ private static func save(pages: String, gpu: String, store: SidebarStore, to chosen: URL?) {+ let stamp: String = {+ let f = DateFormatter()+ f.locale = Locale(identifier: "en_US_POSIX")+ f.dateFormat = "yyyy-MM-dd HH.mm"+ return f.string(from: Date())+ }()+ let name = "Cra Diagnostics \(stamp)"+ guard let destination = chosen ?? askWhere(name + ".zip") else { return }++ let fm = FileManager.default+ let staging = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)+ let folder = staging.appendingPathComponent(name, isDirectory: true)+ try? fm.createDirectory(at: folder, withIntermediateDirectories: true)+ func write(_ text: String, _ file: String) { try? Data(redact(text).utf8).write(to: folder.appendingPathComponent(file)) }++ CraLog.flush()+ write(summary(store: store), "summary.txt")+ write(pages, "pages.txt")+ write(gpu, "gpu.json")+ for (url, file) in [(CraLog.file, "cra.log"), (CraLog.previousFile, "cra.previous.log"),+ (AppPaths.log, "chromium.log"), (CraLog.chromiumPreviousFile, "chromium.previous.log")] {+ if let data = try? Data(contentsOf: url) { write(String(decoding: data, as: UTF8.self), file) }+ }+ // macOS writes one for Cra and for each helper (renderer, GPU) that crashed.+ let reports = fm.homeDirectoryForCurrentUser.appendingPathComponent("Library/Logs/DiagnosticReports", isDirectory: true)+ let weekAgo = Date().addingTimeInterval(-7 * 86400)+ let crashes = ((try? fm.contentsOfDirectory(at: reports, includingPropertiesForKeys: [.contentModificationDateKey])) ?? []).filter {+ $0.lastPathComponent.hasPrefix("Cra") && ((try? $0.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast) > weekAgo+ }+ if !crashes.isEmpty {+ try? fm.createDirectory(at: folder.appendingPathComponent("crashes"), withIntermediateDirectories: true)+ for c in crashes { if let data = try? Data(contentsOf: c) { write(String(decoding: data, as: UTF8.self), "crashes/" + c.lastPathComponent) } }+ }++ try? fm.removeItem(at: destination)+ let ditto = Process()+ ditto.executableURL = URL(fileURLWithPath: "/usr/bin/ditto")+ ditto.arguments = ["-c", "-k", "--keepParent", folder.path, destination.path]+ do {+ try ditto.run()+ ditto.waitUntilExit()+ } catch {+ CraLog.note("diagnostics export failed: \(error.localizedDescription)")+ }+ try? fm.removeItem(at: staging)+ guard ditto.terminationStatus == 0, fm.fileExists(atPath: destination.path) else {+ let alert = NSAlert()+ alert.messageText = "Cra couldn’t save the diagnostics"+ alert.informativeText = "Try another folder."+ alert.runModal()+ return+ }+ CraLog.note("diagnostics exported (\(crashes.count) crash reports)")+ if chosen == nil { NSWorkspace.shared.activateFileViewerSelecting([destination]) }+ }++ private static func askWhere(_ fileName: String) -> URL? {+ let panel = NSSavePanel()+ panel.title = "Export Diagnostics"+ panel.message = "Cra's logs, the state of the pages on screen and recent crash reports. Site names only: no addresses, history, cookies or passwords."+ panel.nameFieldStringValue = fileName+ panel.allowedContentTypes = [.zip]+ panel.directoryURL = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first+ NSApp.activate()+ return panel.runModal() == .OK ? panel.url : nil+ }++ private static func summary(store: SidebarStore) -> String {+ let info = Bundle.main.infoDictionary+ let os = ProcessInfo.processInfo.operatingSystemVersion+ var size = 0+ sysctlbyname("hw.model", nil, &size, nil, 0)+ var model = [CChar](repeating: 0, count: max(size, 1))+ sysctlbyname("hw.model", &model, &size, nil, 0)+ let screens = NSScreen.screens.map { "\(Int($0.frame.width))x\(Int($0.frame.height))@\(Int($0.backingScaleFactor))x" }+ var lines = [+ "Cra \(info?["CFBundleShortVersionString"] as? String ?? "?") (\(info?["CFBundleVersion"] as? String ?? "?"))",+ "Chromium \(CraCEFRuntime.chromiumVersion()), CEF \(CraCEFRuntime.cefVersion())",+ "macOS \(os.majorVersion).\(os.minorVersion).\(os.patchVersion), \(String(cString: model)), \(ProcessInfo.processInfo.physicalMemory >> 30) GB, \(ProcessInfo.processInfo.activeProcessorCount) cores",+ "Displays: \(screens.joined(separator: ", "))",+ "Running from: \(Bundle.main.bundlePath)",+ "Up for: \(Int(ProcessInfo.processInfo.systemUptime / 60)) min (Mac), \(Int(-(NSRunningApplication.current.launchDate ?? Date()).timeIntervalSinceNow / 60)) min (Cra)",+ "Embedded pages: \(EmbeddedPages.isEnabled), Chrome-style hosting: \(CraCEFRuntime.chromeHosting())",+ "",+ "Spaces: \(store.spaces.count), profiles: \(store.profiles.count), tabs: \(store.allTabs().count)",+ ]+ // Sites the user listed (Developer Mode, link routes) are counted, not named.+ if let data = try? JSONEncoder().encode(store.settings),+ var json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] {+ for key in ["developerHosts", "linkRoutes"] { json[key] = (json[key] as? [Any])?.count }+ if let pretty = try? JSONSerialization.data(withJSONObject: json, options: [.prettyPrinted, .sortedKeys]) {+ lines += ["", "Settings:", String(decoding: pretty, as: UTF8.self)]+ }+ }+ // Extensions with webRequest or declarativeNetRequest reset page loading when they start+ // (the blank restored tab fixed in 0.1.22), so their permissions are listed too.+ lines += ["", "Extensions:"]+ for e in ExtensionStore.shared.entries {+ let manifest = (try? Data(contentsOf: e.url.appendingPathComponent("manifest.json")))+ .flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }+ let permissions = ((manifest?["permissions"] as? [Any]) ?? []).compactMap { $0 as? String }+ .filter { $0.hasPrefix("webRequest") || $0.hasPrefix("declarativeNetRequest") || $0 == "proxy" }+ lines.append(" \(e.name) \(e.version) [\(e.extensionID)]\(e.managedByChrome ? " web store" : "")\(permissions.isEmpty ? "" : " " + permissions.joined(separator: ","))")+ }+ return lines.joined(separator: "\n") + "\n"+ }++ /// Addresses keep their scheme and host; the home folder becomes `~`. The single sign-on+ /// hosts IT allowlisted (Chromium's command line in gpu.json) name the user's employer.+ nonisolated static func redact(_ text: String) -> String {+ var s = text.replacingOccurrences(of: NSHomeDirectory(), with: "~")+ for (pattern, template) in [(#"\b((?:https?|wss?|ftp|chrome-extension)://[^/\s"'<>)\]]+)[/?#][^\s"'<>)\]]*"#, "$1/…"),+ (#"(--auth-server-allowlist=)[^\s"]+"#, "$1(set by IT)")] {+ guard let re = try? NSRegularExpression(pattern: pattern) else { continue }+ s = re.stringByReplacingMatches(in: s, range: NSRange(s.startIndex..., in: s), withTemplate: template)+ }+ return s+ }+}diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mmindex 2a8a2fe..3ea60c5 100644--- a/Sources/CraCEF/CraCEF.mm+++ b/Sources/CraCEF/CraCEF.mm@@ -1062,7 +1062,12 @@ public:void OnLoadError(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, ErrorCode errorCode,const CefString& errorText, const CefString& failedUrl) override {- if ((int)errorCode == -3 /* ERR_ABORTED */ || !frame->IsMain()) return;+ if (!frame->IsMain()) return;+ // A tab left blank is often a navigation that failed or was cut off; Help ▸ Export+ // Diagnostics sends this log, so the line names the site only.+ LOG(WARNING) << "Cra: loading " << LogHost(browser, failedUrl) << " failed: " << errorText.ToString() << " ("+ << (int)errorCode << ")";+ if ((int)errorCode == -3 /* ERR_ABORTED */) return;// 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.@@ -1201,20 +1206,30 @@ public:static const char* kStatus[] = {"abnormal termination", "killed", "crashed", "out of memory","launch failed", "integrity failure"};const char* what = status >= 0 && status < TS_NUM_VALUES ? kStatus[status] : "unknown";- LOG(ERROR) << "Cra: renderer for " << PageHost(browser) << " ended: " << what << " (code " << error_code+ LOG(ERROR) << "Cra: renderer for " << LogHost(browser) << " ended: " << what << " (code " << error_code<< ", " << error_string.ToString() << ")";}bool OnRenderProcessUnresponsive(CefRefPtr<CefBrowser> browser,CefRefPtr<CefUnresponsiveProcessCallback> callback) override {- LOG(ERROR) << "Cra: renderer for " << PageHost(browser) << " is unresponsive";+ LOG(ERROR) << "Cra: renderer for " << LogHost(browser) << " is unresponsive";return false; // Chrome's "Page Unresponsive" dialog}- static std::string PageHost(CefRefPtr<CefBrowser> browser) {+ /// The site for chromium.log, which Help ▸ Export Diagnostics sends: never an incognito one+ /// (nor one whose tab is already gone, when that can't be told).+ std::string LogHost(CefRefPtr<CefBrowser> browser, const CefString& url = CefString()) {+ CraBrowser* o = owner_;+ if (!o) return "(closed tab)";+ if (o.isIncognito) return "(incognito)";+ if (!url.empty()) return UrlHost(url);CefRefPtr<CefFrame> frame = browser->GetMainFrame();+ return frame ? UrlHost(frame->GetURL()) : "(no page)";+ }++ static std::string UrlHost(const CefString& url) {CefURLParts parts;- if (!frame || !CefParseURL(frame->GetURL(), parts)) return "(no page)";+ if (!CefParseURL(url, parts)) return "(no page)";std::string host = CefString(&parts.host).ToString();return host.empty() ? CefString(&parts.scheme).ToString() + ":" : host;}diff --git a/docs/development.md b/docs/development.mdindex 8defc0a..1346749 100644--- a/docs/development.md+++ b/docs/development.md@@ -34,8 +34,18 @@ issue when a newer stable CEF is out; `scripts/update-cef.sh` moves the pin.- `vendor/cef` — CEF binary distribution (fetched, not committed)Data lives in `~/Library/Application Support/Cra`: the sidebar and archive as JSON,-`keybindings.json`, cached favicons, `chromium.log` and a Chromium profile folder. Delete-it to start over.+`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) and where Cra put it (view size,+`window=covered` when another window hides it). `chromium.log` holds Chromium's warnings,+failed page loads and crashed renderers. Each launch keeps the last one's as `*.previous.log`.+Logs name sites by host only. Help ▸ Export Diagnostics… zips both with the GPU report,+the on-screen pages' state, settings, extensions and the last week's crash reports, with+addresses cut to their host; `cra://debug?exportDiagnostics=<path>` does the same without+the save panel.## Running a test instance