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.
Library in the sidebar, page sandbox, HTTPS-only, tab sleeping, live folders
Victor992776f80f73
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swiftindex d71378e..1aa0d80 100644--- a/Sources/Cra/App/AppDelegate.swift+++ b/Sources/Cra/App/AppDelegate.swift@@ -18,10 +18,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {private var bootstrapped = falseprivate var pendingURLs: [String] = []private var autoArchiveTimer: Timer?+ private var tabSleepTimer: Timer?private var settingsWindow: NSWindow?private var settingsController: SettingsWindowController?private var isRelaunching = false- private var archiveWindow: NSWindow?private lazy var extensionsMenu = ExtensionsMenu(app: self)/// Arc's Little Arc windows: small, sidebar-less, disposable (see LittleWindowController).private(set) var littleWindows: [LittleWindowController] = []@@ -67,6 +67,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {autoArchiveTimer = Timer.scheduledTimer(withTimeInterval: 1800, repeats: true) { [weak self] _ inTask { @MainActor in self?.store.runAutoArchive() }}+ tabSleepTimer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in+ Task { @MainActor in self?.sleepIdleTabs() }+ }+ LiveFolderManager.shared.start(store: store)// A restart into an update while the user was away leaves the front app alone.if !SoftwareUpdater.shared.launchedByAutoUpdate { NSApp.activate(ignoringOtherApps: true) }DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in self?.installURLEventHandler() }@@ -151,6 +155,22 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {CraCEFRuntime.loadBlockedDomains(fromFile: path, completion: nil)}observeContentBlocking()+ observeHttpsOnly()+ }++ private func sleepIdleTabs() {+ guard store.settings.tabSleepEnabled else { return }+ for w in mainWindows { w.browsers.sleepIdleTabs(hiddenLongerThan: store.settings.tabSleep.seconds) }+ }++ /// Settings > Privacy > "Always use secure connections", live like content blocking.+ private func observeHttpsOnly() {+ let enabled = withObservationTracking {+ store.settings.httpsOnly+ } onChange: { [weak self] in+ Task { @MainActor in self?.observeHttpsOnly() }+ }+ CraCEFRuntime.setHttpsOnlyModeEnabled(enabled)}private func observeContentBlocking() {@@ -505,7 +525,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {case "dismiss":main.dismissTransientUI()settingsWindow?.close()- archiveWindow?.close()default:break}@@ -627,6 +646,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {case "newFolder":let f = store.createFolder(named: "New Folder", in: store.focusedSpace.pinnedContainerID, index: 0)main.sidebarUI.renamingID = f.id+ case "newGitHubLiveFolder":+ guard !main.isIncognito else { break }+ let sid = store.focusedSpace.id+ let isNew = store.liveFolder(.github, inSpace: sid) == nil+ guard let f = store.createLiveFolder(.github, inSpace: sid) else { break }+ store.setExpanded(f.id, true)+ if isNew { LiveFolderManager.shared.refresh(f.id) }case "newSpace": main.showSpaceEditor(space: nil)case "editSpace": if !main.isIncognito { main.showSpaceEditor(space: store.focusedSpace) }case "deleteSpace": if !main.isIncognito { confirmDeleteSpace(store.focusedSpace) }@@ -664,9 +690,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {// Toggle, like Chrome: ⌥⌘I closes the dock when it is already open.if let b = main.currentBrowser { b.hasDevTools ? b.closeDevTools() : b.showDevTools() }case "inspectElement": main.currentBrowser?.showDevTools()- case "viewArchive", "openLibrary": showArchiveWindow()- case "viewDownloads":- NSWorkspace.shared.open(FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0])+ // Arc's Library is a mode of the window's sidebar; ⇧⌘J opens it on Downloads.+ case "openLibrary": main.toggleLibrary()+ case "viewArchive": main.showLibrary(.archive)+ case "viewDownloads": main.showLibrary(.downloads)case "goBack": main.currentBrowser?.goBack()case "goForward": main.currentBrowser?.goForward()case "pinTab": if let c = current { store.togglePinned(c) }@@ -748,23 +775,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {settingsWindow?.makeKeyAndOrderFront(nil)}- func showArchiveWindow() {- if archiveWindow == nil {- let w = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 720, height: 560), styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)- w.title = "Library"- w.contentView = NSHostingView(rootView: ArchiveView(onRestore: { [weak self] id in- self?.useNormalWindow()- self?.store.restoreArchived(id)- self?.archiveWindow?.close()- self?.main.showWindow(nil)- }).environment(store).environment(favicons))- w.isReleasedWhenClosed = false- w.center()- archiveWindow = w- }- archiveWindow?.makeKeyAndOrderFront(nil)- }-// MARK: Menus (Arc's layout)private func item(_ id: String) -> NSMenuItem {diff --git a/Sources/Cra/App/KeyBindings.swift b/Sources/Cra/App/KeyBindings.swiftindex 4d50a24..f20e855 100644--- a/Sources/Cra/App/KeyBindings.swift+++ b/Sources/Cra/App/KeyBindings.swift@@ -162,6 +162,8 @@ final class KeyBindingRegistry {KeyAction(id: "reopenClosedTab", name: "Restore Last Closed Tab", section: .file, shortcuts: [Shortcut("t", cmdShift)], triggers: ["reopen", "undo close", "restore"]),KeyAction(id: "editURL", name: "Open Command Bar", section: .file, shortcuts: [Shortcut("l", cmd)], triggers: ["url", "address", "command bar"]),KeyAction(id: "newFolder", name: "New Folder", section: .file, shortcuts: [], triggers: ["folder"]),+ KeyAction(id: "newGitHubLiveFolder", name: "New GitHub Live Folder", section: .file, shortcuts: [],+ triggers: ["live folder", "pull requests", "github"]),KeyAction(id: "newSpace", name: "New Space…", section: .file, shortcuts: [], triggers: ["space"]),KeyAction(id: "closeWindow", name: "Close Window", section: .file, shortcuts: [Shortcut("w", cmdShift)], inCommandBar: false),KeyAction(id: "closeTab", name: "Close Tab", section: .file, shortcuts: [Shortcut("w", cmd)], triggers: ["close", "archive tab"]),diff --git a/Sources/Cra/Model/LiveFolderModel.swift b/Sources/Cra/Model/LiveFolderModel.swiftnew file mode 100644index 0000000..424031c--- /dev/null+++ b/Sources/Cra/Model/LiveFolderModel.swift@@ -0,0 +1,77 @@+import Foundation++// Live folders: folders that fill themselves from a service and empty as items close.+// Shape follows Arc's AutomaticLiveFolderData (StorableSidebar.json `list.automaticLiveFolderData`:+// dataSource github, filter.github {attributes, hiddenRepositories}, hiddenItems, lastFetch) and the+// cached LiveItem.github.pullRequest in StorableLiveData.json. Dia 1.54 keeps the same GitHub client+// (ARCClients/GitHubClient). Findings and what was verified: docs/live-folders.md.++/// What a live folder is filled from. Arc and Dia also have Bitbucket, Notion, Drive and calendar sources.+enum LiveFolderSource: String, Codable {+ case github+}++/// Which pull requests a GitHub live folder shows. Arc saves `attributes` as a bit mask (7 = all three).+struct GitHubLiveFilter: Codable, Equatable {+ struct Attributes: OptionSet, Codable, Hashable {+ let rawValue: Int+ /// author:@me+ static let authored = Attributes(rawValue: 1)+ /// user-review-requested:@me (asked of you by name)+ static let reviewRequests = Attributes(rawValue: 2)+ /// review-requested:@me, which also covers teams you are on (Arc: "Team Review Requests")+ static let teamReviewRequests = Attributes(rawValue: 4)+ static let all: Attributes = [.authored, .reviewRequests, .teamReviewRequests]+ }++ var attributes: Attributes = .all+ /// "owner/name" of repositories switched off in the folder's menu.+ var hiddenRepositories: [String] = []+}++enum LiveFolderError: String, Codable, Equatable {+ case notSignedIn, rateLimited, unexpectedPage, network+}++struct LiveFolderData: Codable, Equatable {+ var source: LiveFolderSource = .github+ var filter = GitHubLiveFilter()+ /// Items closed out of the folder; they don't come back (Arc: hiddenItems).+ var hiddenItems: [String] = []+ var lastFetch: Date?+ /// Why the last refresh failed; nil once one succeeds.+ var lastError: LiveFolderError?+ /// Organizations that want a SAML sign-in before their pull requests show up (Arc: needsSSO).+ var ssoOrganizations: [String] = []++ init() {}+ init(from decoder: Decoder) throws {+ let c = try decoder.container(keyedBy: CodingKeys.self)+ source = try c.decodeIfPresent(LiveFolderSource.self, forKey: .source) ?? .github+ filter = try c.decodeIfPresent(GitHubLiveFilter.self, forKey: .filter) ?? GitHubLiveFilter()+ hiddenItems = try c.decodeIfPresent([String].self, forKey: .hiddenItems) ?? []+ lastFetch = try c.decodeIfPresent(Date.self, forKey: .lastFetch)+ lastError = try? c.decodeIfPresent(LiveFolderError.self, forKey: .lastError)+ ssoOrganizations = try c.decodeIfPresent([String].self, forKey: .ssoOrganizations) ?? []+ }+}++/// One pull request as the GitHub client reads it (Arc: LiveItem.Data.github.pullRequest).+struct LivePullRequest: Codable, Equatable, Identifiable {+ enum State: String, Codable { case open, draft, merged, closed }++ var owner: String+ var repo: String+ var number: Int+ var title: String+ var author: String?+ var state: State = .open+ var createdByMe = false+ var isAwaitingMyReview = false+ var createdAt: Date?+ var updatedAt: Date?++ var id: String { url }+ var url: String { "https://github.com/\(owner)/\(repo)/pull/\(number)" }+ var repository: String { "\(owner)/\(repo)" }+}diff --git a/Sources/Cra/Model/SidebarModel.swift b/Sources/Cra/Model/SidebarModel.swiftindex 61b1ab6..15a0bd7 100644--- a/Sources/Cra/Model/SidebarModel.swift+++ b/Sources/Cra/Model/SidebarModel.swift@@ -68,6 +68,12 @@ struct TabData: Codable, Equatable {var customIconKey: String?/// Favorite tile background as "#RRGGBB". nil is the theme's tile fill.var tileColor: String?+ /// The live folder item this tab shows (Arc: liveItemID.url), e.g. a pull request URL.+ var liveItemURL: String?+ /// Line under the title that the live folder writes (a pull request's author).+ var liveSubtitle: String?+ /// When its pull request left the live folder's results; the tab goes after a grace period.+ var liveGoneAt: Date?var iconKey: String? { customIconKey ?? faviconKey }@@ -128,6 +134,8 @@ struct SidebarItem: Identifiable, Codable, Equatable {var data: ItemData/// A folder's glyph colour; nil is Auto (it follows the theme).var folderIcon: FolderIconStyle? = nil+ /// Set on a folder that fills itself (Arc: list.automaticLiveFolderData).+ var liveFolder: LiveFolderData? = nilvar tab: TabData? {if case .tab(let t) = data { return t }@@ -135,6 +143,7 @@ struct SidebarItem: Identifiable, Codable, Equatable {}var isTab: Bool { tab != nil }var isFolder: Bool { if case .folder = data { return true }; return false }+ var isLiveFolder: Bool { isFolder && liveFolder != nil }var split: SplitData? {if case .split(let s) = data { return s }return nil@@ -338,6 +347,27 @@ enum AutoArchiveThreshold: String, Codable, CaseIterable, Identifiable {}}+enum TabSleepThreshold: String, Codable, CaseIterable, Identifiable {+ case fifteenMinutes, oneHour, fourHours, twelveHours+ var id: String { rawValue }+ var seconds: TimeInterval {+ switch self {+ case .fifteenMinutes: return 15 * 60+ case .oneHour: return 3600+ case .fourHours: return 4 * 3600+ case .twelveHours: return 12 * 3600+ }+ }+ 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"+ }+ }+}+enum SearchEngine: String, Codable, CaseIterable, Identifiable {case google, duckduckgo, bing, kagivar id: String { rawValue }@@ -398,6 +428,12 @@ struct AppSettings: Codable, Equatable {/// Dia's Tabs ▸ "Clean up tabs I haven't used in:" checkbox; `autoArchive` keeps the/// threshold while this is off.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.+ var tabSleepEnabled: Bool = false+ var tabSleep: TabSleepThreshold = .oneHour+ /// Privacy ▸ "Always use secure connections": Chrome's HTTPS-Only Mode.+ var httpsOnly: Bool = falseinit() {}@@ -495,6 +531,9 @@ extension AppSettings {hapticFeedbackOnReorder = try c.decodeIfPresent(Bool.self, forKey: .hapticFeedbackOnReorder) ?? truewarnBeforeQuitting = try c.decodeIfPresent(Bool.self, forKey: .warnBeforeQuitting) ?? falseautoArchiveEnabled = try c.decodeIfPresent(Bool.self, forKey: .autoArchiveEnabled) ?? true+ 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}}@@ -559,5 +598,8 @@ extension TabData {faviconKey = try c.decodeIfPresent(String.self, forKey: .faviconKey) ?? URL(string: url)?.hostcustomIconKey = try c.decodeIfPresent(String.self, forKey: .customIconKey)tileColor = try c.decodeIfPresent(String.self, forKey: .tileColor)+ liveItemURL = try c.decodeIfPresent(String.self, forKey: .liveItemURL)+ liveSubtitle = try c.decodeIfPresent(String.self, forKey: .liveSubtitle)+ liveGoneAt = try c.decodeIfPresent(Date.self, forKey: .liveGoneAt)}}diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swiftindex ecea866..430c505 100644--- a/Sources/Cra/Services/BrowserManager.swift+++ b/Sources/Cra/Services/BrowserManager.swift@@ -18,6 +18,8 @@ final class TabRuntime {/// The tab switcher's thumbnail, taken while the page was last on screen.var snapshot: NSImage?var snapshotWork: DispatchWorkItem?+ /// When the page last went off screen (nil while shown); tab sleeping counts from here.+ var hiddenAt: Date? = Date()/// Chrome-style hosting: the page's own window (nil until created, or for Alloy).var hostWindow: NSWindow? { browser.hostWindow }init(tabID: UUID, browser: CraBrowser) {@@ -163,12 +165,16 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {/// Show several tabs at once (split view); `focused` gets keyboard focus.func show(_ tabIDs: [UUID], focused: UUID?, focus: Bool) {let newSet = Set(tabIDs)- for previous in visibleTabIDs where !newSet.contains(previous) { leaveTab(previous) }+ for previous in visibleTabIDs where !newSet.contains(previous) {+ leaveTab(previous)+ runtimes[previous]?.hiddenAt = Date()+ }let wasVisible = Set(visibleTabIDs)var shown: [UUID] = []for id in tabIDs {guard let rt = ensureRuntime(for: id) else { shown.append(id); continue }if !wasVisible.contains(id) { returnToTab(rt) }+ rt.hiddenAt = nillet 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@@ -258,6 +264,55 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {rt.browser.close()}+ // 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+ /// loading, playing sound, recording, in Picture in Picture or DevTools, holding typed+ /// text or asking before they close (beforeunload) stay awake.+ func sleepIdleTabs(hiddenLongerThan seconds: TimeInterval) {+ let cutoff = Date().addingTimeInterval(-seconds)+ for (id, rt) in runtimes {+ let b = rt.browser+ guard let hidden = rt.hiddenAt, hidden < cutoff, b.isCreated, !b.isLoading, !b.isInPictureInPicture,+ !b.isCapturingMedia, !b.hasDevTools else { continue }+ b.sendDevToolsMethod("Runtime.evaluate", params: Self.sleepProbe) { [weak self] result, _ in+ DispatchQueue.main.async {+ guard let self, self.runtimes[id]?.browser === b, let h = self.runtimes[id]?.hiddenAt, h < cutoff,+ Self.probeSaysIdle(result) else { return }+ self.unload(id)+ }+ }+ }+ }++ /// true when the page has nothing to lose: no audible media, no edited fields, no+ /// beforeunload handler (closing would ask "Leave site?" on a page nobody is looking at).+ private static let sleepProbe: String = {+ let js = """+ (() => {+ const playing = [...document.querySelectorAll('video,audio')].some(m => !m.paused && !m.ended && !m.muted && m.volume > 0);+ const typed = [...document.querySelectorAll('input,textarea,select')].some(e =>+ e.type === 'checkbox' || e.type === 'radio' ? e.checked !== e.defaultChecked+ : e.tagName === 'SELECT' ? [...e.options].some(o => o.selected !== o.defaultSelected)+ : !['hidden','submit','button','reset','image','file','search'].includes(e.type) && e.value !== e.defaultValue);+ const editing = document.activeElement?.isContentEditable === true;+ const guarded = !!window.onbeforeunload || (getEventListeners(window).beforeunload || []).length > 0;+ return !(playing || typed || editing || guarded);+ })()+ """+ let params: [String: Any] = ["expression": js, "returnByValue": true, "includeCommandLineAPI": true]+ return String(data: try! JSONSerialization.data(withJSONObject: params), encoding: .utf8)!+ }()++ private static func probeSaysIdle(_ result: String?) -> Bool {+ guard let data = result?.data(using: .utf8),+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ json["exceptionDetails"] == nil,+ let value = (json["result"] as? [String: Any])?["value"] as? Bool else { return false }+ return value+ }+/// Drop runtimes whose tabs no longer exist (archived, deleted). A page can't change/// its Chromium profile: one whose tab moved to a space with another profile, or whose/// space switched profiles, closes and loads its URL again there when shown.@@ -359,6 +414,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {// Our own error page is a data: URL; keep the real address in the model.if url.hasPrefix("data:text/html;base64,") { return }store.updateTab(id, url: url)+ if !browser.isIncognito { LiveFolderManager.shared.pageChanged(tab: id, to: url) }delegate?.browserManagerDidUpdate(id)}diff --git a/Sources/Cra/Services/GitHubLiveClient.swift b/Sources/Cra/Services/GitHubLiveClient.swiftnew file mode 100644index 0000000..7d4f00e--- /dev/null+++ b/Sources/Cra/Services/GitHubLiveClient.swift@@ -0,0 +1,308 @@+import Foundation++/// Reads pull requests from github.com with the browser's own GitHub session: no token, no+/// OAuth app. Arc and Dia do it this way (ARCClients/GitHubClient, shared by both): a request+/// made by Chromium with the profile's cookies for `github.com/pulls?q=<search>`, asking for+/// GitHub's JSON (headers GitHub-Verified-Fetch and X-Requested-With) and reading HTML when+/// that's what comes back. "Not signed in to GitHub" is a redirect to /login.+enum GitHubLiveClient {+ struct Page: Equatable {+ var pullRequests: [LivePullRequest] = []+ /// The signed-in user (meta user-login / the payload's viewer), when the page says.+ var viewer: String?+ var ssoOrganizations: [String] = []+ }++ enum Failure: Error, Equatable {+ case notSignedIn, rateLimited, unexpectedPage, network++ var asLiveFolderError: LiveFolderError {+ switch self {+ case .notSignedIn: return .notSignedIn+ case .rateLimited: return .rateLimited+ case .unexpectedPage: return .unexpectedPage+ case .network: return .network+ }+ }+ }++ /// Dia's search terms for its Pull Requests folder (GitHubClient: "is:pr is:open …").+ static func query(for attribute: GitHubLiveFilter.Attributes) -> String {+ let who: String+ switch attribute {+ case .authored: who = "author:@me"+ case .reviewRequests: who = "user-review-requested:@me"+ default: who = "review-requested:@me"+ }+ return "is:pr is:open archived:false \(who) sort:updated-desc"+ }++ static func pullsURL(query: String) -> String {+ var c = URLComponents(string: "https://github.com/pulls")!+ c.queryItems = [URLQueryItem(name: "q", value: query)]+ return c.url!.absoluteString+ }++ static func searchURL(query: String) -> String {+ var c = URLComponents(string: "https://github.com/search")!+ c.queryItems = [URLQueryItem(name: "q", value: query), URLQueryItem(name: "type", value: "pullrequests")]+ return c.url!.absoluteString+ }++ static let jsonHeaders = [+ "Accept": "application/json",+ "X-Requested-With": "XMLHttpRequest",+ "GitHub-Verified-Fetch": "true",+ ]++ // MARK: Responses++ /// Turns one response into pull requests, or says why it can't.+ static func read(status: Int, finalURL: String, body: String) -> Result<Page, Failure> {+ if status == 0 { return .failure(.network) }+ if let path = URL(string: finalURL)?.path, path == "/login" || path.hasPrefix("/session") {+ return .failure(.notSignedIn)+ }+ if status == 429 || (status == 403 && body.localizedCaseInsensitiveContains("rate limit")) { return .failure(.rateLimited) }+ // Signed out, the pulls route answers 404 {"error":"Couldn’t authenticate you"} and the+ // search route an empty result with "logged_in": false (both seen 27 Oct 2026).+ if status == 401 || (body.count < 2000 && body.localizedCaseInsensitiveContains("authenticate you")) { return .failure(.notSignedIn) }+ if body.contains("\"logged_in\":false") { return .failure(.notSignedIn) }+ guard (200..<300).contains(status) else { return .failure(.unexpectedPage) }++ var page = Page()+ page.ssoOrganizations = ssoOrganizations(in: body)+ let trimmed = body.trimmingCharacters(in: .whitespacesAndNewlines)+ if trimmed.hasPrefix("{") || trimmed.hasPrefix("[") {+ guard let json = try? JSONSerialization.jsonObject(with: Data(trimmed.utf8)) else { return .failure(.unexpectedPage) }+ page.viewer = viewer(inJSON: json)+ page.pullRequests = pullRequests(inJSON: json)+ return .success(page)+ }+ // An HTML page: logged out pages carry an empty user-login.+ page.viewer = metaContent("user-login", in: body) ?? metaContent("octolytics-actor-login", in: body)+ if page.viewer?.isEmpty ?? true, body.contains("name=\"user-login\"") { return .failure(.notSignedIn) }+ var found: [LivePullRequest] = []+ var sawPayload = false+ for blob in embeddedJSON(in: body) {+ guard let json = try? JSONSerialization.jsonObject(with: Data(blob.utf8)) else { continue }+ sawPayload = true+ if page.viewer?.isEmpty ?? true { page.viewer = viewer(inJSON: json) }+ found += pullRequests(inJSON: json)+ }+ if found.isEmpty { found = pullRequests(inHTML: body) }+ page.pullRequests = unique(found)+ if page.pullRequests.isEmpty && !sawPayload && !body.contains("blankslate") { return .failure(.unexpectedPage) }+ return .success(page)+ }++ // MARK: JSON++ /// Finds pull request objects anywhere in a payload: GitHub's React routes (pulls dashboard,+ /// search) and GraphQL-shaped data name the same facts with different keys.+ static func pullRequests(inJSON root: Any) -> [LivePullRequest] {+ var out: [LivePullRequest] = []+ func walk(_ v: Any, depth: Int) {+ guard depth < 40 else { return }+ if let d = v as? [String: Any] {+ if let pr = pullRequest(from: d) { out.append(pr); return }+ for (_, child) in d { walk(child, depth: depth + 1) }+ } else if let a = v as? [Any] {+ for child in a { walk(child, depth: depth + 1) }+ }+ }+ walk(root, depth: 0)+ return unique(out)+ }++ static func pullRequest(from d: [String: Any]) -> LivePullRequest? {+ let typename = (d["__typename"] as? String) ?? (d["type"] as? String) ?? ""+ if !typename.isEmpty, typename != "PullRequest", !typename.lowercased().contains("pull") { return nil }+ guard let number = int(d["number"]) ?? int(d["num"]) else { return nil }+ guard let rawTitle = (d["title"] as? String) ?? (d["hl_title"] as? String) ?? (d["titleHTML"] as? String) else { return nil }+ let link = ["url", "permalink", "html_url", "resourcePath", "path", "href"].lazy.compactMap { d[$0] as? String }.first+ var owner: String?, repo: String?+ if let link, let m = pullPath(link), m.number == number { owner = m.owner; repo = m.repo }+ if owner == nil, let r = repository(d["repository"] ?? d["repo"] ?? d["repoNameWithOwner"] ?? d["repository_nwo"]) {+ owner = r.owner; repo = r.repo+ }+ guard let owner, let repo else { return nil }+ // Search results carry no link: issue.issue.pull_request_id, merged and reviewable_state+ // say it's a pull request (blackbirdSearchRoute, 27 Oct 2026).+ let issue = (d["issue"] as? [String: Any])?["issue"] as? [String: Any]+ let isPull = link.map { $0.contains("/pull/") } ?? false || typename == "PullRequest"+ || d["isDraft"] != nil || d["is_draft"] != nil || d["reviewDecision"] != nil || d["pull_request"] != nil+ || issue?["pull_request_id"] != nil || d["reviewable_state"] != nil || d["merged"] != nil+ guard isPull || d["num"] != nil else { return nil }++ var pr = LivePullRequest(owner: owner, repo: repo, number: number, title: plainText(rawTitle))+ pr.author = login(d["author"]) ?? login(d["user"]) ?? (d["author_name"] as? String) ?? (d["authorLogin"] as? String)+ let state = ((d["state"] as? String) ?? "open").lowercased()+ if state == "merged" || (d["merged"] as? Bool) == true || (d["mergedAt"] as? String) != nil || (d["merged_at"] as? String) != nil {+ pr.state = .merged+ } else if state == "closed" {+ pr.state = .closed+ } else if state == "draft" || (d["isDraft"] as? Bool) == true || (d["is_draft"] as? Bool) == true || (d["draft"] as? Bool) == true {+ pr.state = .draft+ }+ pr.createdAt = date(d["createdAt"] ?? d["created_at"] ?? d["created"])+ pr.updatedAt = date(d["updatedAt"] ?? d["updated_at"] ?? d["updated"])+ return pr+ }++ static func viewer(inJSON root: Any) -> String? {+ var found: String?+ func walk(_ v: Any, depth: Int) {+ guard found == nil, depth < 12 else { return }+ if let d = v as? [String: Any] {+ for key in ["viewer", "currentUser", "current_user"] {+ if let l = login(d[key]) { found = l; return }+ }+ if let l = (d["current_user_login"] as? String) ?? (d["viewerLogin"] as? String), !l.isEmpty { found = l; return }+ for (_, child) in d { walk(child, depth: depth + 1) }+ } else if let a = v as? [Any] {+ for child in a { walk(child, depth: depth + 1) }+ }+ }+ walk(root, depth: 0)+ return found+ }++ // MARK: HTML++ /// The JSON GitHub's React pages embed (react-app / react-partial embeddedData).+ static func embeddedJSON(in html: String) -> [String] {+ matches(#"<script[^>]*type="application/json"[^>]*>([\s\S]*?)</script>"#, in: html).compactMap { $0.count > 1 ? $0[1] : nil }+ }++ /// The classic issue list (`.js-issue-row`): a pull request link titled with the+ /// pull request, the author's hovercard link after "opened … by".+ static func pullRequests(inHTML html: String) -> [LivePullRequest] {+ let chunks = html.components(separatedBy: "js-issue-row")+ var out: [LivePullRequest] = []+ for chunk in chunks.count > 1 ? Array(chunks.dropFirst()) : chunks {+ for m in matches(#"<a\b([^>]*)>([\s\S]*?)</a>"#, in: chunk) where m.count > 2 {+ let attrs = m[1]+ guard let href = attribute("href", in: attrs), let p = pullPath(href), href.hasSuffix("/pull/\(p.number)") else { continue }+ let hovercard = attribute("data-hovercard-type", in: attrs)+ guard hovercard == "pull_request" || attrs.contains("markdown-title") || attrs.contains("js-navigation-open") else { continue }+ let title = plainText(m[2])+ guard !title.isEmpty else { continue }+ var pr = LivePullRequest(owner: p.owner, repo: p.repo, number: p.number, title: title)+ if let by = matches(#"<a\b[^>]*data-hovercard-type="user"[^>]*>([\s\S]*?)</a>"#, in: chunk).first, by.count > 1 {+ pr.author = plainText(by[1])+ }+ if chunk.contains("octicon-git-pull-request-draft") { pr.state = .draft }+ if let t = matches(#"<relative-time[^>]*datetime="([^"]+)""#, in: chunk).first, t.count > 1 { pr.createdAt = date(t[1]) }+ out.append(pr)+ if chunks.count > 1 { break }+ }+ }+ return unique(out)+ }++ /// Orgs whose pull requests stay hidden until a SAML sign-in: links to /orgs/<org>/sso, and the+ /// search route's `protected_org_logins` (orgs it left out of the results).+ static func ssoOrganizations(in body: String) -> [String] {+ var seen: [String] = []+ var found = matches(#"/orgs/([A-Za-z0-9_.-]+)/sso"#, in: body).compactMap { $0.count > 1 ? $0[1] : nil }+ for list in matches(#""protected_org_logins"\s*:\s*\[([^\]]*)\]"#, in: body) where list.count > 1 {+ found += matches(#""([A-Za-z0-9_.-]+)""#, in: list[1]).compactMap { $0.count > 1 ? $0[1] : nil }+ }+ for org in found where !seen.contains(org) { seen.append(org) }+ return seen+ }++ // MARK: Helpers++ static func pullPath(_ link: String) -> (owner: String, repo: String, number: Int)? {+ guard let m = matches(#"(?:^|github\.com)/([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+)/pull/(\d+)"#, in: link).first, m.count > 3,+ let n = Int(m[3]) else { return nil }+ return (m[1], m[2], n)+ }++ private static func repository(_ v: Any?) -> (owner: String, repo: String)? {+ if let s = v as? String {+ let parts = s.split(separator: "/")+ return parts.count == 2 ? (String(parts[0]), String(parts[1])) : nil+ }+ guard let d = v as? [String: Any] else { return nil }+ if let inner = d["repository"] { return repository(inner) }+ if let nwo = d["nameWithOwner"] as? String ?? d["name_with_owner"] as? String ?? d["full_name"] as? String { return repository(nwo) }+ guard let name = d["name"] as? String else { return nil }+ let owner = login(d["owner"]) ?? (d["owner"] as? String) ?? (d["owner_login"] as? String) ?? (d["ownerLogin"] as? String)+ return owner.map { ($0, name) }+ }++ private static func login(_ v: Any?) -> String? {+ guard let d = v as? [String: Any] else { return nil }+ // The signed-in pulls dashboard sends author {displayLogin, displayName} (27 Oct 2026).+ let l = (d["login"] as? String) ?? (d["displayLogin"] as? String) ?? (d["display_login"] as? String)+ return l?.isEmpty == false ? l : nil+ }++ private static func int(_ v: Any?) -> Int? {+ if let i = v as? Int { return i }+ if let s = v as? String { return Int(s) }+ return nil+ }++ private static let isoFull: ISO8601DateFormatter = {+ let f = ISO8601DateFormatter()+ f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+ return f+ }()+ private static let iso = ISO8601DateFormatter()++ static func date(_ v: Any?) -> Date? {+ if let s = v as? String { return iso.date(from: s) ?? isoFull.date(from: s) }+ if let n = v as? Double { return Date(timeIntervalSince1970: n > 1e11 ? n / 1000 : n) }+ if let n = v as? Int { return Date(timeIntervalSince1970: Double(n) > 1e11 ? Double(n) / 1000 : Double(n)) }+ return nil+ }++ static func metaContent(_ name: String, in html: String) -> String? {+ for m in matches(#"<meta\b[^>]*>"#, in: html) {+ guard attribute("name", in: m[0]) == name else { continue }+ return attribute("content", in: m[0]).map(decodeEntities)+ }+ return nil+ }++ private static func attribute(_ name: String, in tag: String) -> String? {+ matches(#"(?:^|\s)"# + NSRegularExpression.escapedPattern(for: name) + #"="([^"]*)""#, in: tag).first.flatMap { $0.count > 1 ? $0[1] : nil }+ }++ /// Text of a title that may hold markup (search highlights <em>, emoji spans) and entities.+ static func plainText(_ s: String) -> String {+ let stripped = s.replacingOccurrences(of: #"<[^>]+>"#, with: "", options: .regularExpression)+ return decodeEntities(stripped).components(separatedBy: .whitespacesAndNewlines).filter { !$0.isEmpty }.joined(separator: " ")+ }++ private static func decodeEntities(_ s: String) -> String {+ guard s.contains("&") else { return s }+ var out = s+ for (k, v) in ["<": "<", ">": ">", """: "\"", "'": "'", "'": "'", "'": "'", " ": " "] {+ out = out.replacingOccurrences(of: k, with: v)+ }+ for m in matches(#"&#(x?)([0-9a-fA-F]+);"#, in: out) where m.count > 2 {+ if let code = UInt32(m[2], radix: m[1].isEmpty ? 10 : 16), let scalar = Unicode.Scalar(code) {+ out = out.replacingOccurrences(of: m[0], with: String(Character(scalar)))+ }+ }+ return out.replacingOccurrences(of: "&", with: "&")+ }++ private static func matches(_ pattern: String, in s: String) -> [[String]] {+ guard let re = try? NSRegularExpression(pattern: pattern) else { return [] }+ let ns = s as NSString+ return re.matches(in: s, range: NSRange(location: 0, length: ns.length)).map { m in+ (0..<m.numberOfRanges).map { i in m.range(at: i).location == NSNotFound ? "" : ns.substring(with: m.range(at: i)) }+ }+ }++ private static func unique(_ prs: [LivePullRequest]) -> [LivePullRequest] {+ var seen = Set<String>()+ return prs.filter { seen.insert($0.url.lowercased()).inserted }+ }+}diff --git a/Sources/Cra/Services/LiveFolderManager.swift b/Sources/Cra/Services/LiveFolderManager.swiftnew file mode 100644index 0000000..d0574f4--- /dev/null+++ b/Sources/Cra/Services/LiveFolderManager.swift@@ -0,0 +1,173 @@+import AppKit+import CraCEF+import Observation++/// Keeps live folders current on Dia's schedule (its LiveFolderRefreshTrigger: periodicRefresh,+/// windowFocus, manualRefresh, configChanged, externalTrigger): every two minutes while a Cra window+/// is active, when a window takes focus, when the user asks, and right after a pull request is+/// created or reviewed in a tab. See docs/live-folders.md, "Dia's refresh timing".+@MainActor+@Observable+final class LiveFolderManager {+ static let shared = LiveFolderManager()+ @ObservationIgnored private weak var store: SidebarStore?+ /// Folders with a refresh in flight; their refresh button spins.+ private(set) var refreshing: Set<UUID> = []+ /// Repositories in each folder's last results plus the hidden ones: the folder menu's list+ /// (Arc: "This list is generated based on your currently active pull requests.").+ private(set) var repositories: [UUID: [String]] = [:]+ @ObservationIgnored private var timer: Timer?+ /// The last address each tab reported, to tell what a page came from.+ @ObservationIgnored private var lastURL: [UUID: String] = [:]++ /// Dia's github-live-folder-min-refresh-interval-seconds (120 in its flag cache, 27 Oct 2026).+ nonisolated static let refreshInterval: TimeInterval = 120+ /// Dia's github-live-folder-post-merge/-post-review-retention-seconds (120 each): a pull request+ /// that left the results stays this long before its tab goes.+ nonisolated static let retention: TimeInterval = 120+ /// After a pull request is created or reviewed, refreshes this long after (GitHub's search+ /// catches up within seconds, sometimes later).+ static let triggerDelays: [TimeInterval] = [5, 45]+ /// Arc's requestedTooSoon: clicks on refresh closer together than this do nothing.+ static let minimumInterval: TimeInterval = 10+ /// CRA_LIVE_FOLDER_DEBUG=1 writes every GitHub response to <data dir>/live-folder-debug/.+ private static let debug = ProcessInfo.processInfo.environment["CRA_LIVE_FOLDER_DEBUG"] == "1"++ func start(store: SidebarStore) {+ self.store = store+ timer = Timer.scheduledTimer(withTimeInterval: 15, repeats: true) { [weak self] _ in+ Task { @MainActor in+ self?.store?.expireLiveItems(olderThan: Self.retention)+ self?.refreshStale()+ }+ }+ // Dia's windowFocus trigger. App activation makes a window key too.+ NotificationCenter.default.addObserver(forName: NSWindow.didBecomeKeyNotification, object: nil, queue: .main) { [weak self] _ in+ Task { @MainActor in self?.refreshStale() }+ }+ // Chromium's profiles load first.+ DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in self?.refreshStale() }+ }++ /// Dia waits for an active window (LiveDataRefreshSkipReason.waitingForActiveWindow): nothing+ /// is fetched while Cra is in the background.+ func refreshStale(olderThan age: TimeInterval = refreshInterval) {+ guard NSApp.isActive else { return }+ for f in store?.liveFolders ?? [] {+ let last = f.liveFolder?.lastFetch ?? .distantPast+ if Date().timeIntervalSince(last) >= age { refresh(f.id) }+ }+ }++ /// `force` skips the gap between refreshes: the folder's filters just changed.+ func refresh(_ id: UUID, force: Bool = false) {+ guard let store, let live = store.item(id)?.liveFolder, !refreshing.contains(id) else { return }+ if !force, let last = live.lastFetch, Date().timeIntervalSince(last) < Self.minimumInterval, live.lastError == nil { return }+ let attributes: [GitHubLiveFilter.Attributes] = [.authored, .reviewRequests, .teamReviewRequests]+ .filter { live.filter.attributes.contains($0) }+ refreshing.insert(id)+ let profile = store.profilePath(item: id)+ Task { @MainActor in+ var pages: [(GitHubLiveFilter.Attributes, GitHubLiveClient.Page)] = []+ var failure: GitHubLiveClient.Failure?+ for a in attributes {+ switch await fetch(GitHubLiveClient.query(for: a), profile: profile, label: "\(a.rawValue)") {+ case .success(let page): pages.append((a, page))+ case .failure(let f): failure = failure == .notSignedIn ? failure : f+ }+ }+ refreshing.remove(id)+ guard let store = self.store, store.item(id)?.isLiveFolder == true else { return }+ // A partial update would empty the folder of whatever the failed search found.+ if let failure {+ store.applyLiveFailure(failure.asLiveFolderError, to: id)+ return+ }+ let prs = Self.merge(pages)+ let hidden = store.item(id)?.liveFolder?.filter.hiddenRepositories ?? []+ repositories[id] = Array(Set(prs.map(\.repository) + hidden)).sorted { $0.lowercased() < $1.lowercased() }+ let sso = Array(Set(pages.flatMap { $0.1.ssoOrganizations })).sorted()+ store.applyLiveResults(prs, to: id, ssoOrganizations: sso)+ }+ }++ /// A page in a tab moved (BrowserManager). Creating a pull request (compare page → pull page)+ /// and submitting a review (#pullrequestreview- anchor) refresh the folders straight away, like+ /// Dia's edit/review creation triggers; the next refresh moves a new pull request's tab into the folder.+ func pageChanged(tab: UUID, to url: String) {+ let old = lastURL[tab]+ lastURL[tab] = url+ if lastURL.count > 500 { lastURL = [tab: url] }+ guard old != url, let pr = GitHubLiveClient.pullPath(url), !(store?.liveFolders.isEmpty ?? true) else { return }+ let oldPath = old.flatMap { URL(string: $0)?.path } ?? ""+ let created = oldPath.hasPrefix("/\(pr.owner)/\(pr.repo)/compare")+ let reviewed = url.contains("#pullrequestreview-") && !(old ?? "").contains("#pullrequestreview-")+ guard created || reviewed else { return }+ for delay in Self.triggerDelays {+ DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in+ for f in self?.store?.liveFolders ?? [] { self?.refresh(f.id, force: true) }+ }+ }+ }++ /// One search: the pulls page first (what Arc and Dia read), then GitHub's search page+ /// when that comes back with nothing it can read.+ private func fetch(_ query: String, profile: String?, label: String) async -> Result<GitHubLiveClient.Page, GitHubLiveClient.Failure> {+ let pulls = await get(GitHubLiveClient.pullsURL(query: query), profile: profile, label: "pulls-\(label)")+ if case .success(let page) = pulls, !page.pullRequests.isEmpty { return pulls }+ if case .failure(let f) = pulls, f != .unexpectedPage { return pulls }+ let search = await get(GitHubLiveClient.searchURL(query: query), profile: profile, label: "search-\(label)")+ if case .success = search { return search }+ return pulls+ }++ private func get(_ url: String, profile: String?, label: String) async -> Result<GitHubLiveClient.Page, GitHubLiveClient.Failure> {+ await withCheckedContinuation { continuation in+ CraCEFRuntime.fetchURL(url, headers: GitHubLiveClient.jsonHeaders, profilePath: profile) { status, finalURL, mime, body in+ if Self.debug { Self.dump(label: label, url: url, status: status, finalURL: finalURL, mime: mime, body: body) }+ continuation.resume(returning: GitHubLiveClient.read(status: status, finalURL: finalURL, body: body))+ }+ }+ }++ /// One list from the folder's searches: who made it and who's asked come from the search+ /// it was found by, and from the author when the page names the signed-in user.+ static func merge(_ pages: [(GitHubLiveFilter.Attributes, GitHubLiveClient.Page)]) -> [LivePullRequest] {+ let viewer = pages.lazy.compactMap { $0.1.viewer }.first { !$0.isEmpty }?.lowercased()+ var byURL: [String: LivePullRequest] = [:]+ var order: [String] = []+ for (attribute, page) in pages {+ for var pr in page.pullRequests {+ if attribute == .authored { pr.createdByMe = true } else { pr.isAwaitingMyReview = true }+ if let viewer, pr.author?.lowercased() == viewer { pr.createdByMe = true }+ if var seen = byURL[pr.url] {+ seen.createdByMe = seen.createdByMe || pr.createdByMe+ seen.isAwaitingMyReview = seen.isAwaitingMyReview || pr.isAwaitingMyReview+ seen.author = seen.author ?? pr.author+ seen.createdAt = seen.createdAt ?? pr.createdAt+ seen.updatedAt = seen.updatedAt ?? pr.updatedAt+ byURL[pr.url] = seen+ } else {+ byURL[pr.url] = pr+ order.append(pr.url)+ }+ }+ }+ // Newest first, like Arc's folder (its tabs carry the pull request's creation date).+ let rank = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($1, $0) })+ return order.compactMap { byURL[$0] }.sorted {+ let a = $0.createdAt ?? $0.updatedAt, b = $1.createdAt ?? $1.updatedAt+ if let a, let b, a != b { return a > b }+ return rank[$0.url]! < rank[$1.url]!+ }+ }++ private static func dump(label: String, url: String, status: Int, finalURL: String, mime: String, body: String) {+ let dir = AppPaths.file("live-folder-debug")+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ let text = "GET \(url)\nstatus \(status)\nfinal \(finalURL)\nmime \(mime)\n\n\(body)"+ let file = dir.appendingPathComponent("\(label).txt")+ try? text.write(to: file, atomically: true, encoding: .utf8)+ try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: file.path)+ }+}diff --git a/Sources/Cra/Services/SidebarStore.swift b/Sources/Cra/Services/SidebarStore.swiftindex 03707e3..11b4860 100644--- a/Sources/Cra/Services/SidebarStore.swift+++ b/Sources/Cra/Services/SidebarStore.swift@@ -61,7 +61,6 @@ final class SidebarStore {activeWindowID = prefs.windows[0].idlastNormalWindowID = activeWindowIDsplitSharedFavorites(doc.favoritesContainerID)- resolveWindowConflicts(winner: activeWindowID)}/// Make sure every space has its containers and no item points at a@@ -160,7 +159,6 @@ final class SidebarStore {}private func touch() {- resolveWindowConflicts(winner: activeWindowID)revision &+= 1save()}@@ -249,24 +247,6 @@ final class SidebarStore {for c in [space.favoritesContainerID, space.pinnedContainerID, space.todayContainerID] { walk(c) }}- /// A page is one Chromium browser, so it is on screen in one window at a time:- /// when two windows would show the same tab, the winner keeps it and the other- /// window drops its open tab in that space (it shows the empty space instead).- private func resolveWindowConflicts(winner: UUID, wins: Bool = true) {- guard prefs.windows.count > 1 else { return }- let me = prefs.windows.filter { $0.id == winner }, others = prefs.windows.filter { $0.id != winner }- var claimed = Set<UUID>()- for w in wins ? me + others : others + me {- let sid = focusedSpaceID(window: w.id)- let panes = visiblePaneTabIDs(in: sid, window: w.id)- if claimed.isDisjoint(with: panes) {- claimed.formUnion(panes)- } else {- updateWindow(w.id) { $0.selectedTabPerSpace[sid] = nil }- }- }- }-// MARK: Lookupvar orderedSpaces: [Space] { spaceOrder.compactMap { spaces[$0] } }@@ -420,7 +400,6 @@ final class SidebarStore {ranking.recentlySwitchedToTabs[id] = datesrankingFile.save(ranking)}- resolveWindowConflicts(winner: w)touch()}@@ -431,7 +410,8 @@ final class SidebarStore {if !isPinned(id) { t.savedURL = url }if let key = FaviconCache.key(for: url) { t.faviconKey = key }}- if let title { t.savedTitle = title }+ // A live folder's tab keeps the pull request's title (Arc shows that, not the page's).+ if let title, !(t.liveItemURL.map { t.url.hasPrefix($0) } ?? false) { t.savedTitle = title }it.data = .tab(t)items[id] = itrevision &+= 1@@ -534,13 +514,6 @@ final class SidebarStore {.prefix(limit).map(\.id)}- /// The tab last used in a space before `id` (where Arc goes after "Close and Keep Pinned").- func mostRecentTab(in sid: UUID, excluding id: UUID) -> UUID? {- visibleTabs(in: sid)- .filter { $0.id != id && $0.tab?.timeLastActiveAt != nil }- .max { $0.tab!.timeLastActiveAt! < $1.tab!.timeLastActiveAt! }?.id- }-// MARK: Tree moves/// Detach an item from its parent without deleting it.@@ -574,6 +547,10 @@ final class SidebarStore {return}let fromParent = it.parentID+ // A live folder fills itself: nothing is dropped into it, and it never unpacks into Today.+ if items[newParent]?.isLiveFolder == true, fromParent != newParent { return }+ if it.isLiveFolder, case .today? = rootContainerKind(newParent) { return }+ if fromParent != newParent, let from = fromParent, items[from]?.isLiveFolder == true { hideLiveItem(id, in: from) }let oldIndex = fromParent.flatMap { items[$0]?.children.firstIndex(of: id) }if it.isFolder, case .today? = rootContainerKind(newParent) {// Unpack: move the folder's tabs instead.@@ -589,6 +566,7 @@ final class SidebarStore {return}detach(id)+ it = items[id] ?? itvar parent = items[newParent]!var at = index ?? parent.children.countif fromParent == newParent, let old = oldIndex, old < at { at -= 1 }@@ -937,6 +915,11 @@ final class SidebarStore {func deleteFolder(_ id: UUID) {guard let f = items[id], f.isFolder else { return }+ // A live folder's tabs are the service's items, not the user's: they go with it.+ if f.isLiveFolder {+ for c in f.children { items[c] = nil }+ items[id]?.children = []+ }for t in tabs(under: id) { archiveTab(t.id, reason: .manual) }// Nested folders left behind (now empty) go too.for c in children(of: id) where c.isFolder { deleteFolder(c.id) }@@ -957,14 +940,151 @@ final class SidebarStore {if prefs.collapsedPinnedSpaces.remove(spaceID) == nil { prefs.collapsedPinnedSpaces.insert(spaceID) }}+ // MARK: Live folders++ var liveFolders: [SidebarItem] { items.values.filter(\.isLiveFolder) }++ /// The space's live folder for a source (Dia: one Pull Requests folder per space).+ func liveFolder(_ source: LiveFolderSource, inSpace sid: UUID) -> SidebarItem? {+ liveFolders.first { $0.liveFolder?.source == source && spaceID(ofItem: $0.id) == sid }+ }++ /// Arc's "Pull Requests" folder at the top of the space's pinned tabs, open.+ @discardableResult+ func createLiveFolder(_ source: LiveFolderSource, inSpace sid: UUID) -> SidebarItem? {+ if let existing = liveFolder(source, inSpace: sid) { return existing }+ guard let space = spaces[sid], !isIncognito(space: sid) else { return nil }+ let folder = createFolder(named: "Pull Requests", in: space.pinnedContainerID, index: 0)+ items[folder.id]?.liveFolder = LiveFolderData()+ touch()+ return items[folder.id]+ }++ func updateLiveFolder(_ id: UUID, _ change: (inout LiveFolderData) -> Void) {+ guard var live = items[id]?.liveFolder else { return }+ change(&live)+ items[id]?.liveFolder = live+ touch()+ }++ /// A refresh came back. New pull requests come in unread at their place (a Today tab already+ /// showing one moves in instead, Dia's reparentPullRequestTabToLiveFolder), ones that left the+ /// results stay for LiveFolderManager.retention before they go, the rest keep the pull request's+ /// title and author. The first fill marks nothing unread.+ func applyLiveResults(_ prs: [LivePullRequest], to folderID: UUID, ssoOrganizations: [String]) {+ guard var folder = items[folderID], var live = folder.liveFolder else { return }+ let hidden = Set(live.hiddenItems)+ let hiddenRepos = Set(live.filter.hiddenRepositories.map { $0.lowercased() })+ let wanted = prs.filter { !hidden.contains($0.url) && !hiddenRepos.contains($0.repository.lowercased()) }+ var existing: [String: UUID] = [:]+ for c in children(of: folderID) { if let u = c.tab?.liveItemURL { existing[u] = c.id } }+ // Nothing in it yet from a refresh that worked: what arrives now isn't news.+ let firstFill = live.lastFetch == nil || (live.lastError != nil && existing.isEmpty)+ var order: [UUID] = []+ for pr in wanted {+ let subtitle = pr.createdByMe ? nil : pr.author+ if let id = existing.removeValue(forKey: pr.url) ?? adoptableTab(for: pr, folderID: folderID),+ var it = items[id], var t = it.tab {+ if it.parentID != folderID {+ detach(id)+ it.parentID = folderID+ t.savedURL = pr.url+ }+ t.savedTitle = pr.title+ t.liveItemURL = pr.url+ t.liveSubtitle = subtitle+ t.liveGoneAt = nil+ it.data = .tab(t)+ items[id] = it+ order.append(id)+ } else {+ var tab = SidebarItem.tab(pr.url, title: pr.title, parent: folderID)+ var t = TabData(url: pr.url, title: pr.title)+ t.liveItemURL = pr.url+ t.liveSubtitle = subtitle+ tab.data = .tab(t)+ tab.isUnread = !firstFill+ tab.createdAt = pr.createdAt ?? Date()+ items[tab.id] = tab+ order.append(tab.id)+ }+ }+ // Gone from the results (merged, reviewed, closed): marked now, removed once the grace is over.+ for id in existing.values {+ guard var it = items[id], var t = it.tab, t.liveGoneAt == nil else { continue }+ t.liveGoneAt = Date()+ it.data = .tab(t)+ items[id] = it+ }+ folder = items[folderID] ?? folder+ folder.children = order + folder.children.filter { !order.contains($0) && items[$0] != nil }+ live.lastFetch = Date()+ live.lastError = nil+ live.ssoOrganizations = ssoOrganizations+ folder.liveFolder = live+ items[folderID] = folder+ touch()+ }++ /// Live tabs whose pull request left the results longer than `age` ago go; one open in a+ /// window stays until it isn't.+ func expireLiveItems(olderThan age: TimeInterval) {+ let open = Set(prefs.windows.flatMap { $0.selectedTabPerSpace.values })+ var changed = false+ for folder in liveFolders {+ for c in children(of: folder.id) where !open.contains(c.id) {+ guard let goneAt = c.tab?.liveGoneAt, Date().timeIntervalSince(goneAt) >= age else { continue }+ detach(c.id)+ items[c.id] = nil+ changed = true+ }+ }+ if changed { touch() }+ }++ /// A Today tab in the folder's space already on this pull request (the one you just opened).+ private func adoptableTab(for pr: LivePullRequest, folderID: UUID) -> UUID? {+ guard let sid = spaceID(ofItem: folderID), let space = spaces[sid] else { return nil }+ return children(of: space.todayContainerID).first { c in+ guard let url = c.tab?.url, let p = GitHubLiveClient.pullPath(url) else { return false }+ return p.owner.lowercased() == pr.owner.lowercased() && p.repo.lowercased() == pr.repo.lowercased() && p.number == pr.number+ }?.id+ }++ func applyLiveFailure(_ error: LiveFolderError, to folderID: UUID) {+ updateLiveFolder(folderID) {+ $0.lastFetch = Date()+ $0.lastError = error+ }+ }++ /// Remembers a tab leaving its live folder so the next refresh doesn't bring it back;+ /// the tab itself becomes an ordinary one.+ private func hideLiveItem(_ id: UUID, in folderID: UUID) {+ guard var it = items[id], var t = it.tab, let url = t.liveItemURL, var live = items[folderID]?.liveFolder else { return }+ if !live.hiddenItems.contains(url) { live.hiddenItems.append(url) }+ // Arc keeps a short list; old pull requests are long closed.+ if live.hiddenItems.count > 200 { live.hiddenItems.removeFirst(live.hiddenItems.count - 200) }+ items[folderID]?.liveFolder = live+ t.liveItemURL = nil+ t.liveSubtitle = nil+ it.data = .tab(t)+ items[id] = it+ }+// MARK: Archivefunc archiveTab(_ id: UUID, reason: ArchiveReason) {- guard let it = items[id], it.isTab else { return }+ guard var it = items[id], it.isTab else { return }let sid = spaceID(ofItem: id)let selectedIn = sid.map { s in prefs.windows.filter { $0.selectedTabPerSpace[s] == id }.map(\.id) } ?? []let pinned = isPinned(id)let split = splitContaining(id)+ // Closed out of a live folder: the item stays out (Arc: hiddenItems).+ if let p = it.parentID, items[p]?.isLiveFolder == true {+ hideLiveItem(id, in: p)+ it = items[id] ?? it+ }detach(id)items[id] = nil// Empty panes never had a page and incognito pages leave no trace: nothing for the Library.@@ -1151,12 +1271,12 @@ final class SidebarStore {touch()}- /// A window switching to a space whose open tab another window shows leaves it there.+ /// Two windows can have the same tab open; its page shows in the one in use+ /// (MainWindowController.refresh).func focusSpace(_ id: UUID, window: UUID? = nil) {let w = self.window(window).idguard spaces[id] != nil, id != focusedSpaceID(window: w), !self.window(w).isIncognito, !isIncognito(space: id) else { return }updateWindow(w) { $0.focusedSpaceID = id }- resolveWindowConflicts(winner: w, wins: false)revision &+= 1}diff --git a/Sources/Cra/Services/SoftwareUpdater.swift b/Sources/Cra/Services/SoftwareUpdater.swiftindex 79d27d2..3860302 100644--- a/Sources/Cra/Services/SoftwareUpdater.swift+++ b/Sources/Cra/Services/SoftwareUpdater.swift@@ -56,6 +56,12 @@ final class SoftwareUpdater: NSObject {didSet { updater?.automaticallyDownloadsUpdates = automaticallyUpdates }}private(set) var isAvailable = false+ /// Settings ▸ Advanced, next to Check for Updates: when Sparkle last looked.+ var lastCheckSummary: String {+ guard isAvailable else { return "Development builds don’t update." }+ guard let date = updater?.lastUpdateCheckDate else { return "Not checked yet." }+ return "Last checked " + RelativeDateTimeFormatter().localizedString(for: date, relativeTo: Date()) + "."+ }/// This launch came from an automatic restart, so it should not take focus.private(set) var launchedByAutoUpdate = falsediff --git a/Sources/Cra/Services/SuggestionEngine.swift b/Sources/Cra/Services/SuggestionEngine.swiftindex 1508685..023f3c9 100644--- a/Sources/Cra/Services/SuggestionEngine.swift+++ b/Sources/Cra/Services/SuggestionEngine.swift@@ -234,7 +234,7 @@ final class SuggestionEngine {}}if currentTabID != nil {- for f in store.children(of: store.focusedSpace.pinnedContainerID) where f.isFolder {+ for f in store.children(of: store.focusedSpace.pinnedContainerID) where f.isFolder && !f.isLiveFolder {let name = f.title ?? "Folder"let m = nameScore("Move Tab to Folder \(name)", triggers: [name.lowercased()])if m > 0 {diff --git a/Sources/Cra/UI/Settings/AdvancedPane.swift b/Sources/Cra/UI/Settings/AdvancedPane.swiftindex c767655..d2d420d 100644--- a/Sources/Cra/UI/Settings/AdvancedPane.swift+++ b/Sources/Cra/UI/Settings/AdvancedPane.swift@@ -16,6 +16,11 @@ struct AdvancedPane: View {SettingsFormRow(label: "General:") {SettingsCheckbox(title: "Automatically update Cra", isOn: $updater.automaticallyUpdates).disabled(!updater.isAvailable)+ HStack(spacing: 8) {+ Button("Check for Updates…") { updater.checkForUpdates(nil) }+ .disabled(!updater.isAvailable)+ Text(updater.lastCheckSummary).font(.system(size: 11)).foregroundStyle(.secondary)+ }SettingsCheckbox(title: "Chrome engine for pages (extensions, Chrome DevTools)", isOn: $store.settings.chromeEngine)Text("Restart Cra to apply an engine change.").font(.system(size: 11)).foregroundStyle(.secondary)}diff --git a/Sources/Cra/UI/Settings/PrivacyPane.swift b/Sources/Cra/UI/Settings/PrivacyPane.swiftindex db8b513..dc4aab6 100644--- a/Sources/Cra/UI/Settings/PrivacyPane.swift+++ b/Sources/Cra/UI/Settings/PrivacyPane.swift@@ -2,7 +2,8 @@ import SwiftUI/// Dia's Privacy pane: a "Content blocking" card of switch rows with coloured glyphs/// (Block ads / Block cookie banners / Block trackers) and a "Data" card. Cra ships one-/// ad-and-tracker domain list, so it has one switch and no usage-data row.+/// ad-and-tracker domain list, so it has one switch and no usage-data row; "Connections"+/// is Chrome's "Always use secure connections".struct PrivacyPane: View {@Environment(SidebarStore.self) private var store@@ -22,6 +23,20 @@ struct PrivacyPane: View {}}SettingsFootnote("Requests to known ad and tracker domains are cancelled unless they are first-party to the page.")++ SettingsHeader("Connections").padding(.top, 20)+ SettingsCard {+ SettingsCardRow {+ HStack(spacing: 5.5) {+ SettingsGlyph(symbol: "lock.fill", color: Color(nsColor: .systemGreen))+ Text("Always use secure connections").font(.system(size: 13))+ }+ } trailing: {+ Toggle("Always use secure connections", isOn: $store.settings.httpsOnly)+ .toggleStyle(.switch).labelsHidden()+ }+ }+ SettingsFootnote("Pages load over HTTPS. Before opening a site that doesn’t support it, Cra warns you first.")}}}diff --git a/Sources/Cra/UI/Settings/ShortcutsPane.swift b/Sources/Cra/UI/Settings/ShortcutsPane.swiftindex 105fdd2..01d53b2 100644--- a/Sources/Cra/UI/Settings/ShortcutsPane.swift+++ b/Sources/Cra/UI/Settings/ShortcutsPane.swift@@ -251,6 +251,7 @@ enum ShortcutDescriptions {"reopenClosedTab": "Bring back the tab you closed last.","editURL": "Open the command bar to search or enter a URL.","newFolder": "Create a folder in the sidebar.",+ "newGitHubLiveFolder": "Add a folder that fills itself with your open pull requests and review requests.","newSpace": "Create a new space.","closeWindow": "Close the current window.","closeTab": "Close the current tab.",diff --git a/Sources/Cra/UI/Settings/TabsPane.swift b/Sources/Cra/UI/Settings/TabsPane.swiftindex 1d91521..2450116 100644--- a/Sources/Cra/UI/Settings/TabsPane.swift+++ b/Sources/Cra/UI/Settings/TabsPane.swift@@ -36,6 +36,18 @@ 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.swiftindex a59c792..8c9d8ce 100644--- a/Sources/Cra/UI/ShellView.swift+++ b/Sources/Cra/UI/ShellView.swift@@ -86,6 +86,8 @@ final class ShellView: NSView {}var sidebarWidth: CGFloat = CraMetrics.sidebarDefaultWidth { didSet { needsLayout = true } }+ /// Off while the Library has the sidebar: its width is not the user's to drag.+ var sidebarResizable = true { didSet { needsLayout = true } }var sidebarVisible = true { didSet { needsLayout = true } }var floatingSidebar = false { didSet { needsLayout = true } }var contentFullscreen = false { didSet { needsLayout = true } }@@ -488,7 +490,7 @@ final class ShellView: NSView {func apply(_ f: Frames) {if !sidebarDetached { sidebarHost.frame = f.sidebar }resizeHandle.frame = f.handle- resizeHandle.isHidden = f.handle.isEmpty+ resizeHandle.isHidden = f.handle.isEmpty || !sidebarResizablecontentContainer.frame = f.contentcardCornerRadius = f.cornerRadiussidebarHost.layer?.cornerRadius = f.sidebarCorner@@ -641,7 +643,39 @@ final class ShellView: NSView {/// Hosts the SwiftUI sidebar. The window is movable by its background; while/// the pointer is over a draggable row or tile the window controller turns that/// off, so a press starts SwiftUI's `.draggable` instead of a window drag.-final class SidebarHostingView: NSHostingView<AnyView> {}+final class SidebarHostingView: NSHostingView<AnyView> {+ /// SwiftUI's hosting view turns down the click that brings an inactive window forward, so+ /// that click only activates Cra. Controls marked `.actsOnFirstClick()` take it too: after+ /// an automatic update Cra restarts in the background, and "See What's New" took two clicks.+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool {+ if let event, FirstClickArea.Anchor.contains(event) { return true }+ return super.acceptsFirstMouse(for: event)+ }+}++/// Marks the area of a sidebar control that acts on the window's activating click.+private struct FirstClickArea: NSViewRepresentable {+ func makeNSView(context: Context) -> Anchor { Anchor() }+ func updateNSView(_ nsView: Anchor, context: Context) {}++ final class Anchor: NSView {+ private static let all = NSHashTable<Anchor>.weakObjects()++ override init(frame: NSRect) {+ super.init(frame: frame)+ Self.all.add(self)+ }+ required init?(coder: NSCoder) { fatalError() }++ static func contains(_ event: NSEvent) -> Bool {+ all.allObjects.contains { $0.window === event.window && $0.bounds.contains($0.convert(event.locationInWindow, from: nil)) }+ }+ }+}++extension View {+ func actsOnFirstClick() -> some View { background(FirstClickArea().allowsHitTesting(false)) }+}/// Thin vertical strip between sidebar and content that drags the width.final class ResizeHandleView: NSView {diff --git a/Sources/Cra/UI/Sidebar/LibraryView.swift b/Sources/Cra/UI/Sidebar/LibraryView.swiftnew file mode 100644index 0000000..cbb80f4--- /dev/null+++ b/Sources/Cra/UI/Sidebar/LibraryView.swift@@ -0,0 +1,383 @@+import AppKit+import SwiftUI++/// The Library's pages Cra has (Arc's rail also lists Media, Easels, Spaces and Boosts).+enum LibraryPage: String, CaseIterable {+ case downloads, archive++ var title: String { self == .downloads ? "Downloads" : "Archived Tabs" }+ var symbol: String { self == .downloads ? "arrow.down.circle" : "archivebox" }+ var selectedSymbol: String { self == .downloads ? "arrow.down.circle.fill" : "archivebox.fill" }+ var searchPrompt: String { self == .downloads ? "Search Downloads…" : "Search Archive…" }+}++/// Arc's Library: not a window but a mode of the sidebar (WindowState+Library, HomeButton/*),+/// so it never ends up behind the browser. Measured on Arc 1.170 (window captures + AX tree,+/// 1728×1084 window, 27 Oct 2026):+/// - The sidebar widens from 347 to 417 pt: a 113 pt rail (a faint white wash brightening+/// toward its right edge, ending in a 1 pt hairline) and the page's list.+/// - Rail buttons 97×80 at x 8, 100 pt apart, the group centred vertically: an 18 pt glyph+/// 22 pt from the top, the 12 pt semibold label under it (white 60 %). The page shown gets+/// a white 7 % fill and its glyph filled in the space's accent.+/// - The list column: a 36 pt search field ("Search Archive…") from x 120 and a Filter button+/// at the top, 10 pt from the window top; day headers ("Today", 13 pt semibold); rows 56 pt+/// apart with a 24 pt icon at x 130, the title at x 164 (14 pt) and the URL under it (12 pt).+/// - A back arrow (32×32 at x 8, 8 pt above the bottom) leaves the Library.+/// - Arc leaves it by the shortcut, Escape, that arrow or a swipe (LibraryCloseSource), never by+/// clicking elsewhere, and reopens it on the page last shown.+/// - Opening takes 2–3 frames (the Library slides in from a little to the left); closing slides+/// it left over ~0.1 s while the tab list fades back in.+enum LibraryMetrics {+ static let rail: CGFloat = 113+ /// Arc's Library sidebar was 70 pt wider than the 347 pt tab sidebar.+ static let extraWidth: CGFloat = 70+}++struct LibraryView: View {+ let page: LibraryPage+ let palette: SpacePalette+ @Environment(SidebarUIState.self) private var ui+ @Environment(\.sidebarActions) private var actions++ var body: some View {+ HStack(spacing: 0) {+ rail+ LibraryList(page: page, palette: palette)+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)+ }+ .foregroundStyle(palette.textPrimary)+ .onExitCommand { actions.closeLibrary() }+ }++ private var ink: Color { palette.isDark ? .white : .black }++ private var rail: some View {+ VStack(spacing: 0) {+ Spacer(minLength: CraMetrics.titleAreaHeight)+ VStack(spacing: 20) {+ ForEach(LibraryPage.allCases, id: \.self) { p in+ LibraryRailButton(page: p, selected: p == page, palette: palette) { actions.showLibrary(p) }+ }+ }+ Spacer(minLength: 0)+ HStack {+ SidebarIconButton(symbol: "arrow.left", palette: palette, help: "Exit the Library (Esc)", size: 32, height: 32,+ iconSize: 15, weight: .regular) { actions.closeLibrary() }+ Spacer(minLength: 0)+ }+ .padding(.leading, 8)+ .padding(.bottom, 8)+ }+ .frame(width: LibraryMetrics.rail - 1)+ .frame(maxHeight: .infinity)+ .background(LinearGradient(colors: [ink.opacity(0.02), ink.opacity(0.045)], startPoint: .leading, endPoint: .trailing))+ .overlay(alignment: .trailing) { Rectangle().fill(ink.opacity(0.09)).frame(width: 1).offset(x: 1) }+ .padding(.trailing, 1)+ }+}++private struct LibraryRailButton: View {+ let page: LibraryPage+ let selected: Bool+ let palette: SpacePalette+ let action: () -> Void+ @State private var hover = false+ private var ink: Color { palette.isDark ? .white : .black }++ var body: some View {+ Button(action: action) {+ VStack(spacing: 0) {+ Image(systemName: selected ? page.selectedSymbol : page.symbol)+ .font(.system(size: 17, weight: .medium))+ .symbolRenderingMode(selected ? .palette : .monochrome)+ .foregroundStyle(selected ? AnyShapeStyle(.white) : AnyShapeStyle(ink.opacity(0.6)),+ selected ? AnyShapeStyle(Color.accentColor) : AnyShapeStyle(ink.opacity(0.6)))+ .frame(height: 20)+ .padding(.top, 21)+ Text(page.title)+ .font(.system(size: 12, weight: .semibold))+ .foregroundStyle(ink.opacity(selected ? 0.82 : 0.6))+ .lineLimit(1)+ .padding(.top, 9)+ Spacer(minLength: 0)+ }+ .frame(width: 97, height: 80)+ .background(RoundedRectangle(cornerRadius: 12, style: .continuous)+ .fill(ink.opacity(selected ? 0.07 : (hover ? 0.04 : 0))))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .onHover { hover = $0 }+ .accessibilityLabel(page.title)+ }+}++/// The page's list column: search, then the downloads or the archived tabs by day.+private struct LibraryList: View {+ let page: LibraryPage+ let palette: SpacePalette+ @Environment(SidebarStore.self) private var store+ @Environment(\.sidebarActions) private var actions+ @State private var query = ""+ @FocusState private var searchFocused: Bool+ private var ink: Color { palette.isDark ? .white : .black }++ var body: some View {+ VStack(spacing: 0) {+ searchRow+ .padding(.top, 10)+ .padding(.leading, 7)+ .padding(.trailing, 8)+ ScrollView {+ LazyVStack(alignment: .leading, spacing: 0, pinnedViews: []) {+ switch page {+ case .downloads: downloads+ case .archive: archive+ }+ }+ .padding(.bottom, 12)+ }+ .scrollIndicators(.never)+ }+ .onChange(of: page) { _, _ in query = "" }+ .onAppear { searchFocused = true }+ }++ private var searchRow: some View {+ HStack(spacing: 4) {+ HStack(spacing: 10) {+ Image(systemName: "magnifyingglass")+ .font(.system(size: 14))+ .foregroundStyle(ink.opacity(0.5))+ TextField(page.searchPrompt, text: $query)+ .textFieldStyle(.plain)+ .font(.system(size: 14))+ .focused($searchFocused)+ }+ .padding(.horizontal, 12)+ .frame(height: 36)+ .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(ink.opacity(0.08)))+ menu+ }+ }++ /// Arc's Filter button; Cra's holds the page's actions.+ private var menu: some View {+ Menu {+ switch page {+ case .downloads:+ Button("Open Downloads Folder") {+ NSWorkspace.shared.open(FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0])+ }+ case .archive:+ Button("Clear Archive") { store.clearArchive() }.disabled(store.archive.isEmpty)+ }+ } label: {+ Image(systemName: "ellipsis")+ .font(.system(size: 14, weight: .medium))+ .foregroundStyle(ink.opacity(0.7))+ .frame(width: 36, height: 36)+ .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(ink.opacity(0.05)))+ .contentShape(Rectangle())+ }+ .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden)+ .frame(width: 36)+ }++ private var needle: String { query.lowercased().trimmingCharacters(in: .whitespaces) }++ // MARK: Downloads++ @ViewBuilder private var downloads: some View {+ let all = DownloadHistory.shared.entries.reversed().filter { FileManager.default.fileExists(atPath: $0.path) }+ let shown = needle.isEmpty ? all : all.filter { ($0.path as NSString).lastPathComponent.lowercased().contains(needle) }+ if shown.isEmpty {+ empty(symbol: "arrow.down.circle", title: all.isEmpty ? "Nothing here yet!" : "No matches",+ detail: all.isEmpty ? "Files you download show up here." : nil)+ } else {+ ForEach(grouped(shown, date: \.date), id: \.0) { label, entries in+ header(label)+ ForEach(entries) { LibraryDownloadRow(entry: $0, palette: palette) }+ }+ }+ }++ // MARK: Archive++ @ViewBuilder private var archive: some View {+ let shown = needle.isEmpty ? store.archive : store.archive.filter {+ $0.item.displayTitle.lowercased().contains(needle) || ($0.item.tab?.url.lowercased().contains(needle) ?? false)+ }+ if shown.isEmpty {+ empty(symbol: "archivebox", title: store.archive.isEmpty ? "Nothing here yet!" : "No matches",+ detail: store.archive.isEmpty ? "Tabs you close end up here." : nil)+ } else {+ ForEach(grouped(shown, date: \.archivedAt), id: \.0) { label, entries in+ header(label)+ ForEach(entries) { e in+ LibraryArchiveRow(entry: e, palette: palette) { actions.restoreArchived(e.id) }+ }+ }+ }+ }++ // MARK: Pieces++ private func header(_ label: String) -> some View {+ Text(label)+ .font(.system(size: 13, weight: .semibold))+ .foregroundStyle(ink.opacity(0.6))+ .padding(.leading, 11)+ .padding(.top, 18)+ .padding(.bottom, 6)+ }++ private func empty(symbol: String, title: String, detail: String?) -> some View {+ VStack(spacing: 8) {+ Image(systemName: symbol)+ .font(.system(size: 30, weight: .light))+ .foregroundStyle(ink.opacity(0.45))+ .padding(.bottom, 4)+ Text(title).font(.system(size: 17, weight: .semibold)).foregroundStyle(ink.opacity(0.9))+ if let detail {+ Text(detail).font(.system(size: 14)).foregroundStyle(ink.opacity(0.7)).multilineTextAlignment(.center)+ }+ }+ .frame(maxWidth: .infinity)+ .padding(.horizontal, 16)+ .padding(.top, 260)+ }++ private func grouped<T>(_ items: [T], date: KeyPath<T, Date>) -> [(String, [T])] {+ let cal = Calendar.current+ let df = DateFormatter()+ df.dateStyle = .medium+ var order: [String] = []+ var groups: [String: [T]] = [:]+ for e in items {+ let d = e[keyPath: date]+ let label = cal.isDateInToday(d) ? "Today" : (cal.isDateInYesterday(d) ? "Yesterday" : df.string(from: d))+ if groups[label] == nil { order.append(label) }+ groups[label, default: []].append(e)+ }+ return order.map { ($0, groups[$0]!) }+ }+}++/// Arc's archive row: 24 pt icon, title over the URL, 56 pt apart.+private struct LibraryArchiveRow: View {+ let entry: ArchivedItem+ let palette: SpacePalette+ let restore: () -> Void+ @Environment(SidebarStore.self) private var store+ @Environment(FaviconCache.self) private var favicons+ @State private var hover = false+ private var ink: Color { palette.isDark ? .white : .black }++ var body: some View {+ Button(action: restore) {+ HStack(spacing: 10) {+ Group {+ if let img = favicons.image(forKey: entry.item.tab?.faviconKey) {+ Image(nsImage: img).resizable().frame(width: 16, height: 16)+ } else {+ Color.clear+ }+ }+ .frame(width: 24, height: 24)+ .background(RoundedRectangle(cornerRadius: 6, style: .continuous).fill(ink.opacity(0.04)))+ VStack(alignment: .leading, spacing: 1) {+ Text(entry.item.displayTitle)+ .font(.system(size: 14))+ .foregroundStyle(ink.opacity(0.82))+ .lineLimit(1)+ Text(SuggestionEngine.humanURL(entry.item.tab?.url ?? ""))+ .font(.system(size: 12))+ .foregroundStyle(ink.opacity(0.55))+ .lineLimit(1).truncationMode(.tail)+ }+ Spacer(minLength: 0)+ }+ .padding(.leading, 9)+ .padding(.trailing, 8)+ .frame(height: 52)+ .background(RoundedRectangle(cornerRadius: 10, style: .continuous).fill(hover ? palette.hoverFill : .clear))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .padding(.horizontal, 4)+ .padding(.vertical, 2)+ .onHover { hover = $0 }+ .arcTooltip(entry.item.tab?.url ?? "")+ .contextMenu {+ Button("Restore", action: restore)+ Button("Copy Link") {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(entry.item.tab?.url ?? "", forType: .string)+ }+ Divider()+ Button("Remove from Archive") { store.removeFromArchive(entry.id) }+ }+ }+}++/// A download: its Quick Look thumbnail, the file name and when it arrived (the hover list's row).+private struct LibraryDownloadRow: View {+ let entry: DownloadHistory.Entry+ let palette: SpacePalette+ @State private var hover = false+ private var ink: Color { palette.isDark ? .white : .black }+ private var url: URL { URL(fileURLWithPath: entry.path) }++ var body: some View {+ Button { NSWorkspace.shared.open(url) } label: {+ HStack(spacing: 10) {+ Group {+ if let image = DownloadHistory.shared.thumbnail(for: entry.path) {+ Image(nsImage: image).resizable().aspectRatio(contentMode: .fill)+ } else {+ ink.opacity(0.04)+ }+ }+ .frame(width: 32, height: 32)+ .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous))+ VStack(alignment: .leading, spacing: 1) {+ Text(url.lastPathComponent)+ .font(.system(size: 14))+ .foregroundStyle(ink.opacity(0.82))+ .lineLimit(1).truncationMode(.middle)+ Text(Self.age.localizedString(for: min(entry.date, Date()), relativeTo: Date()))+ .font(.system(size: 12))+ .foregroundStyle(ink.opacity(0.55))+ .lineLimit(1)+ }+ Spacer(minLength: 0)+ }+ .padding(.leading, 5)+ .padding(.trailing, 8)+ .frame(height: 52)+ .background(RoundedRectangle(cornerRadius: 10, style: .continuous).fill(hover ? palette.hoverFill : .clear))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .padding(.horizontal, 4)+ .padding(.vertical, 2)+ .onHover { hover = $0 }+ .onDrag { NSItemProvider(contentsOf: url) ?? NSItemProvider() }+ .contextMenu {+ Button("Open") { NSWorkspace.shared.open(url) }+ Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([url]) }+ Divider()+ Button("Copy") {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.writeObjects([url as NSURL])+ }+ }+ }++ private static let age: RelativeDateTimeFormatter = {+ let f = RelativeDateTimeFormatter()+ f.unitsStyle = .full+ return f+ }()+}diff --git a/Sources/Cra/UI/Sidebar/LiveFolderViews.swift b/Sources/Cra/UI/Sidebar/LiveFolderViews.swiftnew file mode 100644index 0000000..ed07915--- /dev/null+++ b/Sources/Cra/UI/Sidebar/LiveFolderViews.swift@@ -0,0 +1,239 @@+import AppKit+import SwiftUI++// The parts of a folder row that differ for a live folder (Arc's GitHub "Pull Requests" folder):+// the GitHub glyph, a refresh button, the folder menu with its filters, and a line inside the+// folder when it has nothing to show or GitHub can't be read.++/// GitHub's mark (Primer Octicons mark-github, MIT) for the live folder and its tabs (Arc: the+/// GithubFavicon asset and customInfo.iconType "github"). github.com's own favicon is no stand-in:+/// Cra caches favicons per host and GitHub swaps in a red ✕ while a pull request's checks fail.+enum GitHubMark {+ static let image: NSImage = {+ let svg = #"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"/></svg>"#+ let img = NSImage(data: Data(svg.utf8)) ?? NSImage()+ img.isTemplate = true+ return img+ }()+}++/// The mark on its own: a live folder's tabs (Arc draws GithubFavicon for them).+struct GitHubMarkIcon: View {+ let palette: SpacePalette+ var size: CGFloat = CraMetrics.favicon+ var color: Color?+ var body: some View {+ Image(nsImage: GitHubMark.image)+ .resizable()+ .interpolation(.high)+ .aspectRatio(contentMode: .fit)+ .foregroundStyle(color ?? (palette.isDark ? Color.white.opacity(0.92) : Color.black.opacity(0.85)))+ .frame(width: size, height: size)+ }+}++/// Arc's live folder glyph: the folder it draws for any folder, with GitHub's mark on its+/// front in the outline colour (seen in Arc 1.170, 27 Oct 2026).+struct LiveFolderIcon: View {+ let palette: SpacePalette+ let style: FolderIconStyle?+ let expanded: Bool+ var body: some View {+ let glyph = palette.folderColors(style)+ ZStack {+ if !expanded {+ Image(systemName: "folder.fill").foregroundStyle(glyph.fill)+ }+ Image(systemName: "folder").foregroundStyle(glyph.tint)+ GitHubMarkIcon(palette: palette, size: 7, color: glyph.tint)+ .offset(y: 1.5)+ }+ .font(.system(size: 15, weight: .regular))+ }+}++/// Trailing refresh button. It spins while a refresh runs; a failed refresh leaves a warning+/// in its place until the next one works.+struct LiveFolderAccessory: View {+ let item: SidebarItem+ let palette: SpacePalette+ let hover: Bool+ private var manager: LiveFolderManager { .shared }++ var body: some View {+ let live = item.liveFolder+ let busy = manager.refreshing.contains(item.id)+ if busy {+ ProgressView().controlSize(.mini).frame(width: 26, height: 26)+ } else if let error = live?.lastError {+ // Arc keeps the warning on hover too; here a click tries again.+ SidebarIconButton(symbol: "exclamationmark.triangle", palette: palette, help: "\(LiveFolderText.status(error)). Click to try again.",+ size: 26, iconSize: 13, weight: .regular) {+ manager.refresh(item.id)+ }+ } else if hover {+ SidebarIconButton(symbol: "arrow.clockwise", palette: palette, help: LiveFolderText.refreshHelp(live),+ size: 26, iconSize: 12) {+ manager.refresh(item.id)+ }+ }+ }+}++/// A line inside the open folder when there are no pull requests to show, or GitHub can't be+/// read (Arc's live folder cells: "Sign back in to GitHub.", "Login with SSO to unlock this folder").+struct LiveFolderStatusRow: View {+ let item: SidebarItem+ let depth: Int+ let palette: SpacePalette+ @Environment(SidebarStore.self) private var store+ @Environment(\.sidebarActions) private var actions+ @State private var hover = false++ private var message: (text: String, url: String?)? {+ guard let live = item.liveFolder, item.children.isEmpty else { return nil }+ switch live.lastError {+ case .notSignedIn?: return ("Sign back in to GitHub.", "https://github.com/login")+ case .some: return ("We’re having trouble connecting to GitHub; click here to see your Pull Requests.", "https://github.com/pulls")+ case nil:+ if let org = live.ssoOrganizations.first { return ("Login with SSO to unlock this folder", "https://github.com/orgs/\(org)/sso") }+ if live.lastFetch == nil { return nil }+ return ("Pull requests from you and your team will show up here automatically", nil)+ }+ }++ var body: some View {+ if let message {+ Text(message.text)+ .font(.system(size: 12))+ .foregroundStyle(message.url != nil && hover ? palette.textSecondary : palette.textTertiary)+ .lineLimit(3)+ .fixedSize(horizontal: false, vertical: true)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.leading, 8 + CGFloat(depth) * CraMetrics.indent + CraMetrics.favicon + 11)+ .padding(.trailing, 10)+ .padding(.vertical, 8)+ .background(RoundedRectangle(cornerRadius: CraMetrics.rowCorner, style: .continuous)+ .fill(message.url != nil && hover ? palette.hoverFill : .clear))+ .contentShape(Rectangle())+ .onHover { hover = $0 }+ .onTapGesture { if let url = message.url { actions.openURL(url) } }+ }+ }+}++/// The live folder's context menu (Arc: SidebarMenu+ListContextMenu liveFolderContextMenu).+struct LiveFolderMenu: View {+ let item: SidebarItem+ @Environment(SidebarStore.self) private var store+ @Environment(SidebarUIState.self) private var ui+ @Environment(\.sidebarActions) private var actions+ private var manager: LiveFolderManager { .shared }++ var body: some View {+ let live = item.liveFolder ?? LiveFolderData()+ Text(manager.refreshing.contains(item.id) ? "Updating…" : LiveFolderText.lastUpdate(live))+ Button("Refresh") { manager.refresh(item.id) }+ Divider()+ filterToggle("My Pull Requests", .authored, live)+ filterToggle("Review Requests", .reviewRequests, live)+ filterToggle("Team Review Requests", .teamReviewRequests, live)+ let repos = manager.repositories[item.id] ?? live.filter.hiddenRepositories+ if !repos.isEmpty {+ Menu("Repositories") {+ Text("This list is generated based on your currently active pull requests.")+ Divider()+ ForEach(repos, id: \.self) { repo in+ Toggle(repo, isOn: Binding(+ get: { !live.filter.hiddenRepositories.contains(repo) },+ set: { on in+ store.updateLiveFolder(item.id) { l in+ l.filter.hiddenRepositories.removeAll { $0 == repo }+ if !on { l.filter.hiddenRepositories.append(repo) }+ }+ manager.refresh(item.id, force: true)+ }))+ }+ }+ }+ if !live.ssoOrganizations.isEmpty {+ Divider()+ Text("SSO ensures all of your organizations’ PRs appear")+ ForEach(live.ssoOrganizations, id: \.self) { org in+ Button("Sign In to \(org) with SSO…") { actions.openURL("https://github.com/orgs/\(org)/sso") }+ }+ }+ Divider()+ Button("Rename…") { ui.renamingID = item.id }+ Picker("Icon Color", selection: Binding(get: { item.folderIcon }, set: { store.setFolderIcon($0, for: item.id) })) {+ Text("Auto").tag(FolderIconStyle?.none)+ Text("White").tag(FolderIconStyle?.some(.white))+ Text("Black").tag(FolderIconStyle?.some(.black))+ }+ Button("Copy All Links as Markdown") {+ let lines = store.children(of: item.id).compactMap { c in c.tab.map { "- [\(c.displayTitle)](\($0.liveItemURL ?? $0.url))" } }+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(lines.joined(separator: "\n"), forType: .string)+ }+ .disabled(item.children.isEmpty)+ Divider()+ Button("Delete Live Folder") { confirmDelete() }+ }++ private func filterToggle(_ title: String, _ attribute: GitHubLiveFilter.Attributes, _ live: LiveFolderData) -> some View {+ Toggle(title, isOn: Binding(+ get: { live.filter.attributes.contains(attribute) },+ set: { on in+ store.updateLiveFolder(item.id) { l in+ if on { l.filter.attributes.insert(attribute) } else { l.filter.attributes.remove(attribute) }+ }+ manager.refresh(item.id, force: true)+ }))+ }++ /// Arc asks first ("Delete your %@ Live Folder?") and says how to get it back.+ private func confirmDelete() {+ let alert = NSAlert()+ alert.messageText = "Delete your \(item.title ?? "Pull Requests") Live Folder?"+ alert.informativeText = "You can add it again with New GitHub Live Folder in the sidebar’s menu or the command bar."+ alert.addButton(withTitle: "Delete")+ alert.addButton(withTitle: "Cancel")+ alert.buttons.first?.hasDestructiveAction = true+ let id = item.id+ let delete = { withAnimation(.snappy(duration: 0.22, extraBounce: 0)) { store.deleteFolder(id) } }+ if let window = NSApp.keyWindow {+ alert.beginSheetModal(for: window) { if $0 == .alertFirstButtonReturn { delete() } }+ } else if alert.runModal() == .alertFirstButtonReturn {+ delete()+ }+ }+}++enum LiveFolderText {+ private static let relative: RelativeDateTimeFormatter = {+ let f = RelativeDateTimeFormatter()+ f.unitsStyle = .full+ return f+ }()++ static func lastUpdate(_ live: LiveFolderData) -> String {+ if let error = live.lastError { return status(error) }+ guard let last = live.lastFetch else { return "Not updated yet" }+ if Date().timeIntervalSince(last) < 60 { return "Updated just now" }+ return "Updated \(relative.localizedString(for: last, relativeTo: Date()))"+ }++ static func refreshHelp(_ live: LiveFolderData?) -> String {+ guard let live, live.lastFetch != nil else { return "Refresh" }+ return "Refresh · \(lastUpdate(live))"+ }++ static func status(_ error: LiveFolderError) -> String {+ switch error {+ case .notSignedIn: return "Not signed in to GitHub"+ case .rateLimited: return "GitHub rate limit exceeded"+ case .unexpectedPage: return "Failed to update: unexpected GitHub page"+ case .network: return "Failed to update: GitHub can’t be reached"+ }+ }+}diff --git a/Sources/Cra/UI/Sidebar/SidebarItemView.swift b/Sources/Cra/UI/Sidebar/SidebarItemView.swiftindex 6156b7e..24b94dd 100644--- a/Sources/Cra/UI/Sidebar/SidebarItemView.swift+++ b/Sources/Cra/UI/Sidebar/SidebarItemView.swift@@ -18,6 +18,7 @@ struct SidebarItemView: View {SidebarItemView(item: child, depth: depth + 1, palette: palette, section: section).transition(.asymmetric(insertion: .opacity.combined(with: .offset(y: -6)), removal: .opacity))}+ if item.isLiveFolder { LiveFolderStatusRow(item: item, depth: depth + 1, palette: palette) }}} else if item.isTab {TabRow(item: item, depth: depth, palette: palette, section: section)@@ -83,6 +84,8 @@ struct TabRow: View {/// Arc shows the host under a pinned tab only when it has left the pinned/// site (navigating within the same host shows nothing).private var subtitle: String? {+ // A live folder's pull request by someone else shows its author (Arc's sidebarItemSubtitleTextField).+ if let author = tab.liveSubtitle, URL(string: tab.url)?.host == "github.com" { return author }guard navigatedAway, let host = URL(string: tab.url)?.host, let saved = URL(string: tab.savedURL)?.host,host.replacingOccurrences(of: "www.", with: "") != saved.replacingOccurrences(of: "www.", with: "") else { return nil }return host.replacingOccurrences(of: "www.", with: "")@@ -91,8 +94,14 @@ struct TabRow: View {var body: some View {let session = uiHStack(spacing: 11) {- FaviconView(key: tab.iconKey, palette: palette)- .frame(width: CraMetrics.favicon)+ Group {+ if tab.liveItemURL != nil && tab.customIconKey == nil {+ GitHubMarkIcon(palette: palette)+ } else {+ FaviconView(key: tab.iconKey, palette: palette)+ }+ }+ .frame(width: CraMetrics.favicon)if editing {TextField("", text: $draft).textFieldStyle(.plain)@@ -168,7 +177,11 @@ struct TabRow: View {).overlay { if ui.keyboardFocusID == item.id { FocusRing(radius: CraMetrics.rowCorner) } }.contentShape(Rectangle())- .onHover { hover = $0; ui.hoverDraggable(item.id, $0) }+ .onHover { inside in+ hover = inside+ ui.hoverDraggable(item.id, inside)+ if inside { ui.hoveredTabID = item.id } else if ui.hoveredTabID == item.id { ui.hoveredTabID = nil }+ }.onTapGesture {let event = NSApp.currentEventlet flags = event?.modifierFlags.intersection([.command, .shift]) ?? []@@ -241,7 +254,7 @@ struct TabRow: View {/// Move to Folder / New Folder for this tab, or for every picked tab.@ViewBuilderprivate func folderMenu(_ ids: [UUID]) -> some View {- let folders = store.children(of: store.focusedSpace(window: ui.windowID).pinnedContainerID).filter { $0.isFolder }+ let folders = store.children(of: store.focusedSpace(window: ui.windowID).pinnedContainerID).filter { $0.isFolder && !$0.isLiveFolder }if !folders.isEmpty {Menu(ids.count > 1 ? "Move \(ids.count) Tabs to Folder" : "Move to Folder") {ForEach(folders) { f in@@ -318,14 +331,18 @@ struct FolderRow: View {let session = uilet glyph = palette.folderColors(item.folderIcon)HStack(spacing: 11) {- ZStack {- if !expanded {- Image(systemName: "folder.fill").foregroundStyle(glyph.fill)+ if item.isLiveFolder {+ LiveFolderIcon(palette: palette, style: item.folderIcon, expanded: expanded).frame(width: CraMetrics.favicon)+ } else {+ ZStack {+ if !expanded {+ Image(systemName: "folder.fill").foregroundStyle(glyph.fill)+ }+ Image(systemName: "folder").foregroundStyle(glyph.tint)}- Image(systemName: "folder").foregroundStyle(glyph.tint)+ .font(.system(size: 15, weight: .regular))+ .frame(width: CraMetrics.favicon)}- .font(.system(size: 15, weight: .regular))- .frame(width: CraMetrics.favicon)if editing {TextField("", text: $draft).textFieldStyle(.plain)@@ -341,7 +358,10 @@ struct FolderRow: View {.lineLimit(1)}Spacer()- if hover && !expanded {+ if item.isLiveFolder {+ LiveFolderAccessory(item: item, palette: palette, hover: hover && !editing)+ .padding(.trailing, 7)+ } else if hover && !expanded {Text("\(store.tabs(under: item.id).count)").font(.system(size: 11, weight: .medium)).foregroundStyle(palette.textTertiary)@@ -363,23 +383,32 @@ struct FolderRow: View {}.draggable(SidebarDragItem.begin(item.id, session)).contextMenu {- Button("Rename…") { ui.renamingID = item.id }- Button("New Folder Inside") {- let f = store.createFolder(named: "New Folder", in: item.id, index: 0)- store.setExpanded(item.id, true)- ui.renamingID = f.id- }- Picker("Icon Color", selection: Binding(get: { item.folderIcon }, set: { store.setFolderIcon($0, for: item.id) })) {- Text("Auto").tag(FolderIconStyle?.none)- Text("White").tag(FolderIconStyle?.some(.white))- Text("Black").tag(FolderIconStyle?.some(.black))+ if item.isLiveFolder {+ LiveFolderMenu(item: item)+ } else {+ folderMenu}- Divider()- Button("Delete Folder (archives tabs)") { store.deleteFolder(item.id) }}.modifier(SidebarDropPreview(id: item.id, palette: palette))}+ @ViewBuilder+ private var folderMenu: some View {+ Button("Rename…") { ui.renamingID = item.id }+ Button("New Folder Inside") {+ let f = store.createFolder(named: "New Folder", in: item.id, index: 0)+ store.setExpanded(item.id, true)+ ui.renamingID = f.id+ }+ Picker("Icon Color", selection: Binding(get: { item.folderIcon }, set: { store.setFolderIcon($0, for: item.id) })) {+ Text("Auto").tag(FolderIconStyle?.none)+ Text("White").tag(FolderIconStyle?.some(.white))+ Text("Black").tag(FolderIconStyle?.some(.black))+ }+ Divider()+ Button("Delete Folder (archives tabs)") { store.deleteFolder(item.id) }+ }+private func commitRename() {guard editing else { return }store.rename(item.id, to: draft.isEmpty ? "Folder" : draft)diff --git a/Sources/Cra/UI/Sidebar/SidebarListDrop.swift b/Sources/Cra/UI/Sidebar/SidebarListDrop.swiftindex 5e7cd53..4c40013 100644--- a/Sources/Cra/UI/Sidebar/SidebarListDrop.swift+++ b/Sources/Cra/UI/Sidebar/SidebarListDrop.swift@@ -291,6 +291,14 @@ struct SidebarListDropDelegate: DropDelegate {}}+ // A live folder fills itself: nothing goes into it from outside, and its tabs make no new folders.+ switch target {+ case .into(let f)? where store.item(f)?.isLiveFolder == true: target = nil+ case .insert(let parent, _)? where store.item(parent)?.isLiveFolder == true && store.item(id)?.parentID != parent: target = nil+ case .newFolder(let tab)? where store.item(store.item(tab)?.parentID ?? tab)?.isLiveFolder == true: target = nil+ default: break+ }+var drop = SidebarListDrop(draggedID: id, target: target)guard case .insert(let parent, let index)? = target else { return drop }let kids = store.item(parent)?.children ?? []@@ -365,8 +373,11 @@ struct SidebarDropPreview: ViewModifier {.allowsHitTesting(false)}}- .onGeometryChange(for: CGRect.self) { $0.frame(in: .named(SidebarListDropDelegate.coordinateSpace)) } action: { ui.rowFrames[id] = $0 }.visualEffect { content, _ in content.offset(y: nudge) }+ // Measured outside the nudge: frames that moved with it fed back into the hit test,+ // so a pointer near a row edge fell into the widened gap, the target jumped to the+ // end of the list, the nudge moved away and the target came back, over and over.+ .onGeometryChange(for: CGRect.self) { $0.frame(in: .named(SidebarListDropDelegate.coordinateSpace)) } action: { ui.rowFrames[id] = $0 }}/// This row is being dragged, itself or as one of the picked tabs.diff --git a/Sources/Cra/UI/Sidebar/SidebarRootView.swift b/Sources/Cra/UI/Sidebar/SidebarRootView.swiftindex 98b1056..ed6e3d9 100644--- a/Sources/Cra/UI/Sidebar/SidebarRootView.swift+++ b/Sources/Cra/UI/Sidebar/SidebarRootView.swift@@ -9,9 +9,26 @@ struct SidebarRootView: View {@Environment(\.sidebarActions) private var actionsvar body: some View {+ let palette = store.focusedSpace(window: ui.windowID).theme.palette+ // The Library takes over the sidebar (LibraryView: in from a little to the left,+ // out to the left while the tab list fades back in).+ ZStack(alignment: .topLeading) {+ tabs+ .opacity(ui.libraryPage == nil ? 1 : 0)+ .allowsHitTesting(ui.libraryPage == nil)+ if let page = ui.libraryPage {+ LibraryView(page: page, palette: palette)+ .ignoresSafeArea()+ .transition(.asymmetric(insertion: .offset(x: -24).combined(with: .opacity),+ removal: .offset(x: -LibraryMetrics.rail).combined(with: .opacity)))+ }+ }+ }++ private var tabs: some View {let space = store.focusedSpace(window: ui.windowID)let palette = space.theme.palette- VStack(spacing: 0) {+ return VStack(spacing: 0) {SidebarTopBar(palette: palette)// Dia's paging container: every space's list sits side by side and the// strip follows the swipe 1:1, then a spring settles it on a page.@@ -331,6 +348,8 @@ struct SpaceSectionView: View {private var listMenu: some View {Button("New Tab") { actions.openCommandBar(.newTab) }Button("New Folder") { actions.performAction("newFolder") }+ Button("New GitHub Live Folder") { actions.performAction("newGitHubLiveFolder") }+ .disabled(store.liveFolder(.github, inSpace: space.id) != nil)Divider()if !store.children(of: space.todayContainerID).isEmpty {Button("Clear Today") { store.clearToday(space.id) }@@ -486,6 +505,8 @@ struct SpaceHeader: View {Divider()Button("Edit Space…") { actions.editSpace(space) }Button("New Folder") { actions.performAction("newFolder") }+ Button("New GitHub Live Folder") { actions.performAction("newGitHubLiveFolder") }+ .disabled(store.liveFolder(.github, inSpace: space.id) != nil)Divider()Button("Clear Today") { store.clearToday(space.id) }Divider()diff --git a/Sources/Cra/UI/Sidebar/SpaceDock.swift b/Sources/Cra/UI/Sidebar/SpaceDock.swiftindex 5016bde..7f9b329 100644--- a/Sources/Cra/UI/Sidebar/SpaceDock.swift+++ b/Sources/Cra/UI/Sidebar/SpaceDock.swift@@ -8,17 +8,15 @@ struct SpaceDock: View {@Environment(SidebarUIState.self) private var ui@Environment(\.sidebarActions) private var actions@State private var reorder: SpaceReorder?- @GestureState private var pressing: UUID?+ @State private var hovered: UUID?/// Arc 1.170 (SidebarDock, an NSCollectionView): 34×32 pt cells side by side with no/// gap, so a press anywhere between two icons still lands on a space.static let cell = CGSize(width: 34, height: 32)- /// Marks the strip as draggable content so a press there never moves the window.- private static let stripID = UUID()var body: some View {HStack(spacing: 0) {- LibraryButton(palette: palette) { actions.showArchive() }+ LibraryButton(palette: palette) { actions.toggleLibrary() }Spacer(minLength: 0)// An incognito window has one space of its own: nothing to switch to or add.if !store.window(ui.windowID).isIncognito {@@ -27,20 +25,19 @@ struct SpaceDock: View {ForEach(Array(spaces.enumerated()), id: \.element.id) { index, space inSpaceDockButton(space: space, palette: palette,selected: space.id == store.focusedSpaceID(window: ui.windowID),+ hovered: hovered == space.id && reorder == nil,pressed: reorder?.id == space.id).offset(x: offset(of: space.id, at: index)).zIndex(reorder?.id == space.id ? 1 : 0)- .gesture(press(space, at: index, count: spaces.count))}}- .coordinateSpace(name: Self.stripID)- .background(SpaceDockStripAnchor(ui: ui).allowsHitTesting(false))- .onHover { ui.hoverDraggable(Self.stripID, $0) }- // A cancelled gesture never reaches onEnded; don't leave a cell pressed.- .onChange(of: pressing) { _, now in- guard now == nil else { return }- DispatchQueue.main.async { if reorder?.settling == false { reorder = nil } }- }+ .overlay(SpaceDockMouse(+ cellWidth: Self.cell.width, count: spaces.count,+ hover: { i in hovered = i.map { spaces[$0].id } },+ press: { i in reorder = SpaceReorder(id: spaces[i].id, from: i, to: i) },+ drag: { drag(by: $0, count: spaces.count) },+ release: { inside in release(inside: inside, spaces: spaces) },+ menu: { menu(for: spaces[$0]) }))Spacer(minLength: 0)SidebarIconButton(symbol: "plus", palette: palette, help: "New Space") { actions.editSpace(nil) }}@@ -58,47 +55,59 @@ struct SpaceDock: View {return 0}- /// Arc's dock item handles mouseDown/mouseUp itself: the cell fills on press, a release- /// switches space, and dragging reorders. A release inside the pressed cell that didn't- /// move the space still switches, so a shaky click never ends up as a window drag or a no-op.- private func press(_ space: Space, at index: Int, count: Int) -> some Gesture {- let cell = CGRect(x: CGFloat(index) * Self.cell.width, y: 0, width: Self.cell.width, height: Self.cell.height)- return DragGesture(minimumDistance: 0, coordinateSpace: .named(Self.stripID))- .updating($pressing) { _, state, _ in state = space.id }- .onChanged { g in- var r = reorder ?? SpaceReorder(id: space.id, from: index, to: index)- guard r.id == space.id else { return }- if !r.moved && abs(g.translation.width) < 3 && abs(g.translation.height) < 3 {- reorder = r- return- }- r.moved = true- let w = Self.cell.width- r.dx = min(max(g.translation.width, -CGFloat(index) * w), CGFloat(count - 1 - index) * w)- let to = min(max(index + Int((r.dx / w).rounded()), 0), count - 1)- if to != r.to {- reorder?.dx = r.dx- withAnimation(.easeOut(duration: 0.2)) { r.to = to; reorder = r }- } else {- reorder = r- }- }- .onEnded { g in- guard let r = reorder, r.id == space.id, r.to != r.from else {- if cell.contains(g.location) { store.focusSpace(space.id, window: ui.windowID) }- if reorder?.id == space.id { withAnimation(.easeOut(duration: 0.15)) { reorder = nil } }- return- }- reorder?.settling = true- withAnimation(.easeOut(duration: 0.15)) {- reorder?.dx = CGFloat(r.to - r.from) * Self.cell.width- } completion: {- withTransaction(Transaction(animation: nil)) {- store.moveSpace(r.id, to: r.to)- reorder = nil- }- }+ private func drag(by t: CGSize, count: Int) {+ guard var r = reorder, !r.settling else { return }+ if !r.moved && abs(t.width) < 3 && abs(t.height) < 3 { return }+ r.moved = true+ let w = Self.cell.width+ r.dx = min(max(t.width, -CGFloat(r.from) * w), CGFloat(count - 1 - r.from) * w)+ let to = min(max(r.from + Int((r.dx / w).rounded()), 0), count - 1)+ if to != r.to {+ reorder?.dx = r.dx+ withAnimation(.easeOut(duration: 0.2)) { r.to = to; reorder = r }+ } else {+ reorder = r+ }+ }++ /// A release inside the pressed cell that didn't move the space switches to it, so a+ /// shaky click still counts; a moved space slides into its cell and the order is saved.+ private func release(inside: Bool, spaces: [Space]) {+ guard let r = reorder, !r.settling else { return }+ guard r.to != r.from else {+ if inside { store.focusSpace(r.id, window: ui.windowID) }+ withAnimation(.easeOut(duration: 0.15)) { reorder = nil }+ return+ }+ reorder?.settling = true+ // `moveSpace` indexes the full space order; land next to the space now in that cell.+ let target = store.spaceOrder.firstIndex(of: spaces[r.to].id) ?? r.to+ withAnimation(.easeOut(duration: 0.15)) {+ reorder?.dx = CGFloat(r.to - r.from) * Self.cell.width+ } completion: {+ withTransaction(Transaction(animation: nil)) {+ store.moveSpace(r.id, to: target)+ reorder = nil}+ }+ }++ private func menu(for space: Space) -> NSMenu {+ let menu = NSMenu()+ menu.addItem(BlockMenuItem(title: "Edit Space…") { actions.editSpace(space) })+ menu.addItem(.separator())+ menu.addItem(BlockMenuItem(title: "Move Left") {+ if let i = store.spaceOrder.firstIndex(of: space.id) { store.moveSpace(space.id, to: max(0, i - 1)) }+ })+ menu.addItem(BlockMenuItem(title: "Move Right") {+ if let i = store.spaceOrder.firstIndex(of: space.id) { store.moveSpace(space.id, to: i + 1) }+ })+ menu.addItem(.separator())+ menu.addItem(BlockMenuItem(title: "Delete Space…") {+ store.focusSpace(space.id, window: ui.windowID)+ actions.performAction("deleteSpace")+ })+ return menu}}@@ -112,15 +121,85 @@ private struct SpaceReorder {var settling = false}+/// Arc's dock items take the mouse themselves (SidebarDockItemView overrides mouseDown:/mouseUp:).+/// This AppKit view over the strip does the same, so a press there never moves the window,+/// and every click counts (a SwiftUI drag gesture here dropped every other press).+private struct SpaceDockMouse: NSViewRepresentable {+ let cellWidth: CGFloat+ let count: Int+ let hover: (Int?) -> Void+ let press: (Int) -> Void+ let drag: (CGSize) -> Void+ let release: (_ inside: Bool) -> Void+ let menu: (Int) -> NSMenu++ func makeNSView(context: Context) -> MouseView { MouseView() }+ func updateNSView(_ view: MouseView, context: Context) { view.config = self }++ final class MouseView: NSView {+ var config: SpaceDockMouse?+ private var pressed: (index: Int, start: NSPoint)?+ private var hovered: Int? {+ didSet { if hovered != oldValue { config?.hover(hovered) } }+ }++ override var isFlipped: Bool { true }+ override var mouseDownCanMoveWindow: Bool { false }+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }++ private func point(_ event: NSEvent) -> NSPoint { convert(event.locationInWindow, from: nil) }+ private func cell(_ i: Int) -> NSRect {+ NSRect(x: CGFloat(i) * (config?.cellWidth ?? 34), y: 0, width: config?.cellWidth ?? 34, height: bounds.height)+ }+ private func index(at p: NSPoint) -> Int? {+ guard let config, bounds.contains(p) else { return nil }+ let i = Int(p.x / config.cellWidth)+ return i < config.count ? i : nil+ }++ override func updateTrackingAreas() {+ super.updateTrackingAreas()+ for t in trackingAreas { removeTrackingArea(t) }+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect],+ owner: self))+ }+ override func mouseEntered(with event: NSEvent) { if pressed == nil { hovered = index(at: point(event)) } }+ override func mouseMoved(with event: NSEvent) { if pressed == nil { hovered = index(at: point(event)) } }+ override func mouseExited(with event: NSEvent) { if pressed == nil { hovered = nil } }++ override func mouseDown(with event: NSEvent) {+ let p = point(event)+ guard let i = index(at: p) else { return }+ pressed = (i, p)+ config?.press(i)+ }+ override func mouseDragged(with event: NSEvent) {+ guard let pressed else { return }+ let p = point(event)+ config?.drag(CGSize(width: p.x - pressed.start.x, height: p.y - pressed.start.y))+ }+ override func mouseUp(with event: NSEvent) {+ guard let i = pressed?.index else { return }+ pressed = nil+ let p = point(event)+ config?.release(cell(i).contains(p))+ hovered = index(at: p)+ }+ override func menu(for event: NSEvent) -> NSMenu? {+ index(at: point(event)).flatMap { config?.menu($0) }+ }+ }+}+struct SpaceDockButton: View {let space: Spacelet palette: SpacePalettelet selected: Bool+ var hovered = falsevar pressed = false@Environment(SidebarStore.self) private var store@Environment(SidebarUIState.self) private var ui@Environment(\.sidebarActions) private var actions- @State private var hover = false@State private var targeted = false/// Arc's hovered/pressed cell on a dark space: white at ~7.8% (39,33,51 over 21,14,34), 6 pt corners.@@ -130,11 +209,10 @@ struct SpaceDockButton: View {Text(space.emoji).font(.system(size: 13)).frame(width: SpaceDock.cell.width, height: SpaceDock.cell.height)- .opacity(selected || hover || pressed ? 1 : 0.45)- .saturation(selected || hover || pressed ? 1 : 0.2)- .background(RoundedRectangle(cornerRadius: 6).fill(targeted || hover || pressed ? cellFill : .clear))+ .opacity(selected || hovered || pressed ? 1 : 0.45)+ .saturation(selected || hovered || pressed ? 1 : 0.2)+ .background(RoundedRectangle(cornerRadius: 6).fill(targeted || hovered || pressed ? cellFill : .clear)).contentShape(Rectangle())- .onHover { hover = $0 }.arcTooltip(space.title)// Arc exposes each cell as a button named after the space..accessibilityElement()@@ -154,14 +232,6 @@ struct SpaceDockButton: View {if targeted { store.focusSpace(space.id, window: ui.windowID) }}}- .contextMenu {- Button("Edit Space…") { actions.editSpace(space) }- Divider()- Button("Move Left") { if let i = store.spaceOrder.firstIndex(of: space.id) { store.moveSpace(space.id, to: max(0, i - 1)) } }- Button("Move Right") { if let i = store.spaceOrder.firstIndex(of: space.id) { store.moveSpace(space.id, to: i + 1) } }- Divider()- Button("Delete Space…") { store.focusSpace(space.id, window: ui.windowID); actions.performAction("deleteSpace") }- }}}@@ -267,17 +337,6 @@ private struct BinMotion {var opacity: Double = 1}-/// Hands the strip of space cells to the window, which keeps presses there from dragging it.-private struct SpaceDockStripAnchor: NSViewRepresentable {- let ui: SidebarUIState- func makeNSView(context: Context) -> NSView {- let v = NSView()- ui.spaceDockStrip = v- return v- }- func updateNSView(_ nsView: NSView, context: Context) { ui.spaceDockStrip = nsView }-}-/// Hands the Library button's NSView to the window controller, which aims download/// flights at it (the sidebar can live in the window or in the floating sidebar panel).private struct LibraryAnchor: NSViewRepresentable {diff --git a/Sources/Cra/UI/SidebarUIState.swift b/Sources/Cra/UI/SidebarUIState.swiftindex cd5cffc..fb63f13 100644--- a/Sources/Cra/UI/SidebarUIState.swift+++ b/Sources/Cra/UI/SidebarUIState.swift@@ -30,14 +30,16 @@ final class SidebarUIState {var recentDownload: RecentDownload?/// The Library button's view, where download flights land.@ObservationIgnored weak var libraryAnchor: NSView?- /// The space dock's strip of space cells; a press there never drags the window.- @ObservationIgnored weak var spaceDockStrip: NSView?/// Arc's downloads list over the bottom of the sidebar, open while the Library/// button (or the list) is hovered.var downloadsListOpen = false@ObservationIgnored var libraryHovered = false@ObservationIgnored var downloadsListHovered = false@ObservationIgnored var downloadsListWork: DispatchWorkItem?+ /// The Library page this window's sidebar shows, nil while it shows the tabs (Arc keeps the+ /// Library per window and reopens it on the page last shown).+ var libraryPage: LibraryPage?+ @ObservationIgnored var lastLibraryPage: LibraryPage = .downloads/// Tab chosen from the keyboard; Arc draws its yellow/black dashed ring/// around it until the mouse picks another tab.var keyboardFocusID: UUID?@@ -160,7 +162,11 @@ final class SidebarActions {var reload: () -> Void = {}var editSpace: (Space?) -> Void = { _ in }var toggleSidebar: () -> Void = {}- var showArchive: () -> Void = {}+ var toggleLibrary: () -> Void = {}+ /// The Library in the sidebar: open it on a page, leave it, restore an archived tab from it.+ var showLibrary: (LibraryPage) -> Void = { _ in }+ var closeLibrary: () -> Void = {}+ var restoreArchived: (UUID) -> Void = { _ in }var resetPinnedTab: (UUID) -> Void = { _ in }var openURL: (String) -> Void = { _ in }var performAction: (String) -> Void = { _ in }diff --git a/Sources/Cra/UI/SiteControlCenter.swift b/Sources/Cra/UI/SiteControlCenter.swiftindex 89d253e..cbf94de 100644--- a/Sources/Cra/UI/SiteControlCenter.swift+++ b/Sources/Cra/UI/SiteControlCenter.swift@@ -341,7 +341,7 @@ private struct SiteControlCenterMoreButton: View {}}-private final class BlockMenuItem: NSMenuItem {+final class BlockMenuItem: NSMenuItem {private let block: () -> Voidinit(title: String, action: @escaping () -> Void) {block = actiondiff --git a/Sources/Cra/UI/SplitView/PaneCardView.swift b/Sources/Cra/UI/SplitView/PaneCardView.swiftindex 9613c8f..d9f8c70 100644--- a/Sources/Cra/UI/SplitView/PaneCardView.swift+++ b/Sources/Cra/UI/SplitView/PaneCardView.swift@@ -36,6 +36,16 @@ final class PaneCardView: NSView {var transparent = false { didSet { refreshBackground() } }/// While a pane is being dragged open/closed its page keeps its last size.var frozenWebBounds: NSRect?+ /// The page is on screen in another window: Arc keeps the tab selected here and shows a+ /// blurred snapshot of it (BlurredItemContent) until this window is used again.+ var elsewhereSnapshot: NSImage? {+ didSet {+ guard elsewhereSnapshot !== oldValue else { return }+ elsewhereView.layer?.contents = elsewhereSnapshot.flatMap(Self.blurred)+ }+ }+ var showsElsewhere = false { didSet { elsewhereView.isHidden = !showsElsewhere } }+ private let elsewhereView = NSView()init(tabID: UUID, toolbar: AnyView) {self.tabID = tabID@@ -53,7 +63,13 @@ final class PaneCardView: NSView {toolbarBackground.wantsLayer = truehairline.wantsLayer = truehairline.isHidden = true+ elsewhereView.wantsLayer = true+ elsewhereView.layer?.contentsGravity = .resizeAspectFill+ elsewhereView.layer?.cornerCurve = .continuous+ elsewhereView.layer?.masksToBounds = true+ elsewhereView.isHidden = trueaddSubview(pageBackground)+ addSubview(elsewhereView)addSubview(webArea)addSubview(toolbarBackground)addSubview(hairline)@@ -97,7 +113,22 @@ final class PaneCardView: NSView {pageBackground.layer?.cornerRadius = rounded ? cornerRadius : 0pageBackground.layer?.maskedCorners = th == 0 ? [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]: [.layerMinXMinYCorner, .layerMaxXMinYCorner]+ elsewhereView.frame = fill+ elsewhereView.layer?.cornerRadius = pageBackground.layer?.cornerRadius ?? 0+ elsewhereView.layer?.maskedCorners = pageBackground.layer?.maskedCorners ?? []let wb = frozenWebBounds ?? webArea.boundsfor sub in webArea.subviews where sub.frame != wb { sub.frame = wb }}++ /// The snapshot (the tab switcher's thumbnail of the top of the page), blurred hard enough+ /// that its low resolution doesn't show, cropped back to its own size so the edges stay opaque.+ private static func blurred(_ image: NSImage) -> CGImage? {+ guard let cg = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else { return nil }+ let input = CIImage(cgImage: cg)+ let radius = Double(cg.width) * 0.03+ guard let filter = CIFilter(name: "CIGaussianBlur", parameters: [kCIInputImageKey: input.clampedToExtent(), kCIInputRadiusKey: radius]),+ let output = filter.outputImage?.cropped(to: input.extent),+ let result = CIContext().createCGImage(output, from: input.extent) else { return nil }+ return result+ }}diff --git a/Sources/Cra/UI/Updates/UpdateBanner.swift b/Sources/Cra/UI/Updates/UpdateBanner.swiftindex 9165e42..f0a792e 100644--- a/Sources/Cra/UI/Updates/UpdateBanner.swift+++ b/Sources/Cra/UI/Updates/UpdateBanner.swift@@ -63,6 +63,7 @@ struct UpdateBanner: View {}}.contentShape(RoundedRectangle(cornerRadius: 10, style: .continuous))+ .actsOnFirstClick().onHover { hover = $0 }.onTapGesture { c.action() }.padding(.top, 8)diff --git a/Sources/Cra/UI/Windows/ArchiveView.swift b/Sources/Cra/UI/Windows/ArchiveView.swiftdeleted file mode 100644index fc9effb..0000000--- a/Sources/Cra/UI/Windows/ArchiveView.swift+++ /dev/null@@ -1,100 +0,0 @@-import SwiftUI--/// Searchable list of archived tabs grouped by day (Arc: Archive / ⌘Y).-struct ArchiveView: View {- let onRestore: (UUID) -> Void- @Environment(SidebarStore.self) private var store- @Environment(FaviconCache.self) private var favicons- @State private var query = ""-- private var filtered: [ArchivedItem] {- let q = query.lowercased().trimmingCharacters(in: .whitespaces)- if q.isEmpty { return store.archive }- return store.archive.filter {- $0.item.displayTitle.lowercased().contains(q) || ($0.item.tab?.url.lowercased().contains(q) ?? false)- }- }-- private var grouped: [(String, [ArchivedItem])] {- let cal = Calendar.current- let df = DateFormatter()- df.dateStyle = .medium- var order: [String] = []- var groups: [String: [ArchivedItem]] = [:]- for e in filtered {- let label = cal.isDateInToday(e.archivedAt) ? "Today" : (cal.isDateInYesterday(e.archivedAt) ? "Yesterday" : df.string(from: e.archivedAt))- if groups[label] == nil { order.append(label) }- groups[label, default: []].append(e)- }- return order.map { ($0, groups[$0]!) }- }-- var body: some View {- VStack(spacing: 0) {- HStack {- Image(systemName: "magnifyingglass").foregroundStyle(.secondary)- TextField("Search archived tabs", text: $query).textFieldStyle(.plain)- Spacer()- Text("\(store.archive.count) tabs").foregroundStyle(.secondary).font(.system(size: 12))- Button("Clear Archive") { store.clearArchive() }.disabled(store.archive.isEmpty)- }- .padding(12)- Divider()- if filtered.isEmpty {- Spacer()- Text(store.archive.isEmpty ? "Tabs you close end up here." : "No matches.").foregroundStyle(.secondary)- Spacer()- } else {- List {- ForEach(grouped, id: \.0) { label, items in- Section(label) {- ForEach(items) { e in- ArchiveRow(entry: e)- .contentShape(Rectangle())- .onTapGesture { onRestore(e.id) }- .contextMenu {- Button("Restore") { onRestore(e.id) }- Button("Copy Link") {- NSPasteboard.general.clearContents()- NSPasteboard.general.setString(e.item.tab?.url ?? "", forType: .string)- }- Divider()- Button("Remove from Archive") { store.removeFromArchive(e.id) }- }- }- }- }- }- .listStyle(.inset)- }- }- }-}--private struct ArchiveRow: View {- let entry: ArchivedItem- @Environment(SidebarStore.self) private var store- @Environment(FaviconCache.self) private var favicons- var body: some View {- HStack(spacing: 10) {- if let img = favicons.image(forKey: entry.item.tab?.faviconKey) {- Image(nsImage: img).resizable().frame(width: 16, height: 16).clipShape(RoundedRectangle(cornerRadius: 3))- } else {- Image(systemName: "globe").foregroundStyle(.secondary).frame(width: 16)- }- VStack(alignment: .leading, spacing: 1) {- Text(entry.item.displayTitle).lineLimit(1)- Text(SuggestionEngine.humanURL(entry.item.tab?.url ?? "")).font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1)- }- Spacer()- if let sid = entry.sourceSpaceID, let s = store.space(sid) {- Text("\(s.emoji) \(s.title)").font(.system(size: 11)).foregroundStyle(.secondary)- } else if entry.fromLittleWindow == true {- Text("Little Window").font(.system(size: 11)).foregroundStyle(.secondary)- }- Text(entry.reason == .auto ? "auto" : "").font(.system(size: 10)).foregroundStyle(.tertiary)- Text(entry.archivedAt, style: .time).font(.system(size: 11)).foregroundStyle(.tertiary)- }- .padding(.vertical, 2)- }-}diff --git a/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift b/Sources/Cra/UI/Windows/ExtensionPopupWindow.swiftindex fbf957a..84de6e3 100644--- a/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift+++ b/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift@@ -79,6 +79,23 @@ final class ExtensionPopupWindow: NSWindow {w.observers.append(NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification, object: bubble, queue: .main) { [weak w] _ inMainActor.assumeIsolated { w?.dismiss(closingBubble: false) }})+ // Chrome closes its popup when the popup loses focus, but only once it had focus: shown+ // while the page's own window wasn't key (the button is in Cra's sidebar, or Cra was in+ // the background) it never closed. Give it focus, and close it when another Cra window+ // takes focus or Cra goes to the background, as a focused popup does.+ bubble.makeKey()+ let shownAt = Date()+ w.observers.append(NotificationCenter.default.addObserver(forName: NSWindow.didBecomeKeyNotification, object: nil, queue: .main) { [weak w] note in+ MainActor.assumeIsolated {+ // The click that opened the popup can still be making its window key.+ guard let w, let bubble = w.bubble, let key = note.object as? NSWindow, key !== bubble, key.parent !== bubble,+ Date().timeIntervalSince(shownAt) > 0.3 else { return }+ w.dismiss(closingBubble: true)+ }+ })+ w.observers.append(NotificationCenter.default.addObserver(forName: NSApplication.didResignActiveNotification, object: nil, queue: .main) { [weak w] _ in+ MainActor.assumeIsolated { w?.dismiss(closingBubble: true) }+ })w.observers.append(NotificationCenter.default.addObserver(forName: NSWindow.willMoveNotification, object: w, queue: .main) { [weak w] _ inMainActor.assumeIsolated { w?.dragging = true }})diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swiftindex b70ec67..8c600df 100644--- a/Sources/Cra/UI/Windows/MainWindowController.swift+++ b/Sources/Cra/UI/Windows/MainWindowController.swift@@ -22,6 +22,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMprivate var importWindow: ImportWindowController?private var scrollMonitor: Any?private var childClickMonitor: Any?+ private var middleClickMonitor: Any?private enum SwipeAxis { case undecided, horizontal, vertical }private var swipeAxis = SwipeAxis.verticalprivate var swipeX: CGFloat = 0@@ -105,22 +106,18 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMbrowsers.takeRuntimeFromOtherWindow = { [weak self] id inguard let self else { return nil }for other in self.app.mainWindows where other !== self {- if let rt = other.browsers.release(id) { return rt }+ if let rt = other.browsers.release(id) {+ // The window it came from keeps the tab selected behind a blurred stand-in.+ DispatchQueue.main.async { [weak other] in other?.refresh() }+ return rt+ }}return nil}// AppKit asks the view under a press whether it may move the window. In the// sidebar's list that is SwiftUI's scroll container, which always says yes,// so the window's own flag is what keeps a row press for the row's drag.- sidebarUI.onPointerOverDraggableChange = { [weak window] over in- guard let window, !window.holdingPress else { return }- window.isMovableByWindowBackground = !over- }- window.holdsPress = { [weak window, weak sidebarUI] point in- guard let strip = sidebarUI?.spaceDockStrip, strip.window === window else { return false }- return strip.bounds.contains(strip.convert(point, from: nil))- }- window.movableAfterPress = { [weak sidebarUI] in !(sidebarUI?.pointerOverDraggable ?? false) }+ sidebarUI.onPointerOverDraggableChange = { [weak window] over in window?.isMovableByWindowBackground = !over }browsers.paneHost = { [weak self] id in self?.shell.card(for: id)?.webArea }shell.makeToolbar = { [weak self] id inguard let self else { return AnyView(EmptyView()) }@@ -202,7 +199,14 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM}sidebarActions.editSpace = { [weak self] s in self?.showSpaceEditor(space: s) }sidebarActions.toggleSidebar = { [weak self] in self?.toggleSidebar() }- sidebarActions.showArchive = { [weak self] in self?.app.showArchiveWindow() }+ sidebarActions.toggleLibrary = { [weak self] in self?.toggleLibrary() }+ sidebarActions.showLibrary = { [weak self] page in self?.showLibrary(page) }+ sidebarActions.closeLibrary = { [weak self] in self?.closeLibrary() }+ sidebarActions.restoreArchived = { [weak self] id in+ guard let self else { return }+ _ = self.store.restoreArchived(id)+ self.closeLibrary()+ }sidebarActions.resetPinnedTab = { [weak self] id in self?.resetPinnedTab(id) }sidebarActions.openURL = { [weak self] url inguard let self else { return }@@ -297,13 +301,21 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMlet empty = Set(panes.filter { store.item($0)?.isEmptyTab == true })shell.showToolbar = store.settings.showToolbarshell.setPanes(panes, factors: factors, orientation: split?.split?.orientation ?? .horizontal, focused: selected, empty: empty, animated: true)+ // A page is on screen in one window at a time. Arc keeps the tab selected in every window+ // that has it open: the window in use holds the page, the others show a blurred snapshot+ // until they are used again (windowDidBecomeKey takes the page back).+ let elsewhere = Set(panes.filter(showsElsewhere))+ let live = panes.filter { !elsewhere.contains($0) }+ let liveFocus = selected.flatMap { elsewhere.contains($0) ? nil : $0 }for c in shell.paneCards {c.toolbarHost.rootView = shell.makeToolbar?(c.tabID == ShellView.noTabID ? nil : c.tabID) ?? AnyView(EmptyView())+ c.showsElsewhere = elsewhere.contains(c.tabID)+ c.elsewhereSnapshot = c.showsElsewhere ? app.runtime(for: c.tabID)?.snapshot : nil}sidebarUI.splitPaneIDs = panes.count > 1 ? panes : []- if panes != browsers.visibleTabIDs || selected != browsers.visibleTabID- || panes.contains(where: { browsers.runtime(for: $0) == nil && store.item($0)?.isEmptyTab == false }) {- browsers.show(panes, focused: selected, focus: !commandBar.isOpen)+ if live != browsers.visibleTabIDs || liveFocus != browsers.visibleTabID+ || live.contains(where: { browsers.runtime(for: $0) == nil && store.item($0)?.isEmptyTab == false }) {+ browsers.show(live, focused: liveFocus, focus: !commandBar.isOpen)}shell.layoutContentChildren()syncSidebarUI()@@ -318,10 +330,25 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM}if CGFloat(store.prefs.sidebarWidth) != lastSidebarWidth {lastSidebarWidth = CGFloat(store.prefs.sidebarWidth)- shell.sidebarWidth = lastSidebarWidth+ shell.sidebarWidth = lastSidebarWidth + (sidebarUI.libraryPage != nil ? LibraryMetrics.extraWidth : 0)}}+ /// The browser window the user is in (AppDelegate follows the key window).+ private var isActiveWindow: Bool { store.activeWindowID == windowID }++ /// The tab's page belongs to another window that has it open: the window in use takes it,+ /// others keep it where it is. Windows restored at launch (none has the page yet, and+ /// `app.mainWindows` is still empty) leave it to the window in use, else the first one.+ private func showsElsewhere(_ id: UUID) -> Bool {+ if isActiveWindow || browsers.runtime(for: id) != nil { return false }+ if app.mainWindows.contains(where: { $0 !== self && $0.browsers.runtime(for: id) != nil }) { return true }+ let windows = store.prefs.windows+ let showing = windows.filter { store.visiblePaneTabIDs(in: store.focusedSpaceID(window: $0.id), window: $0.id).contains(id) }+ if showing.contains(where: { $0.id == store.activeWindowID }) { return true }+ return showing.first.map { $0.id != windowID } ?? false+ }+private func syncSidebarUI() {sidebarUI.loadedTabIDs = Set(app.mainWindows.flatMap { $0.browsers.runtimes.keys })let capturing = Set(app.mainWindows.flatMap { $0.browsers.runtimes.filter { $0.value.browser.isCapturingMedia }.keys })@@ -997,8 +1024,12 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM_ = store.resetPinnedTab(id)for w in app.mainWindows { w.browsers.unload(id) }if wasSelected {- // Arc goes back to the tab used before this one.- store.selectTab(store.mostRecentTab(in: focusedSpaceID, excluding: id), window: windowID)+ // Arc goes back to the tab used before this one, if it is still open. A pinned+ // tab that was closed (unloaded) doesn't count: two of them would otherwise hand+ // the selection back and forth on every ⌘W, reloading each other.+ let back = store.recentTabs(in: focusedSpaceID, limit: .max)+ .first { $0 != id && (!store.isPinned($0) || app.runtime(for: $0) != nil) }+ store.selectTab(back, window: windowID)}} else {store.archiveTab(id, reason: .manual)@@ -1047,10 +1078,63 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM// MARK: Sidebarfunc toggleSidebar() {+ if sidebarUI.libraryPage != nil {+ // The Library brought the sidebar out: leaving it hides the sidebar again.+ let showed = libraryShowedSidebar+ closeLibrary()+ if showed { return }+ }sidebarVisible.toggle()if !sidebarVisible { setFloatingSidebar(false) }}+ // MARK: Library++ /// Set when the Library brought a hidden sidebar out; leaving it hides the sidebar again.+ private var libraryShowedSidebar = false++ /// Arc's Library button and ⇧⌘L: open the Library on the page last shown, or leave it.+ func toggleLibrary() {+ if sidebarUI.libraryPage != nil { closeLibrary() } else { showLibrary(sidebarUI.lastLibraryPage) }+ }++ /// The Library takes over the sidebar, which widens for its page rail (LibraryView).+ func showLibrary(_ page: LibraryPage) {+ sidebarUI.lastLibraryPage = page+ let opening = sidebarUI.libraryPage == nil+ withAnimation(.easeOut(duration: 0.05)) { sidebarUI.libraryPage = page }+ guard opening else { return }+ sidebarUI.downloadsListOpen = false+ commandBar.close()+ shell.sidebarResizable = false+ let width = CGFloat(store.prefs.sidebarWidth) + LibraryMetrics.extraWidth+ if sidebarVisible {+ shell.sidebarWidth = width+ shell.animateSidebar(visible: true, floating: false, fullscreen: shell.contentFullscreen, width: width)+ } else {+ setFloatingSidebar(false)+ libraryShowedSidebar = true+ shell.sidebarWidth = width+ sidebarVisible = true+ }+ window?.makeKey()+ }++ func closeLibrary() {+ guard sidebarUI.libraryPage != nil else { return }+ withAnimation(.easeOut(duration: 0.1)) { sidebarUI.libraryPage = nil }+ shell.sidebarResizable = true+ let width = CGFloat(store.prefs.sidebarWidth)+ shell.sidebarWidth = width+ if libraryShowedSidebar {+ libraryShowedSidebar = false+ sidebarVisible = false+ } else {+ shell.animateSidebar(visible: shell.sidebarVisible, floating: false, fullscreen: shell.contentFullscreen, width: width, duration: 0.1)+ }+ currentBrowser?.setFocused(true)+ }+/// Arc's floating sidebar lives in its own panel above the page windows (see FloatingSidebarController).private(set) var floatingSidebar: FloatingSidebarController?@@ -1086,6 +1170,30 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMtarget.makeKey()return event}+ // Middle-click on a sidebar tab closes it, like Arc and Chrome (SwiftUI has no+ // gesture for the middle button; rows report the hovered tab instead).+ middleClickMonitor = NSEvent.addLocalMonitorForEvents(matching: .otherMouseUp) { [weak self] event in+ guard let self, event.buttonNumber == 2, let window = self.window, let target = event.window,+ target === window || target.parent === window, !CraCEFRuntime.isPageWindow(target),+ let id = self.sidebarUI.hoveredTabID else { return event }+ self.middleClickClose(id)+ return nil+ }+ }++ /// What the row's hover button does: close every picked tab when this is one of them;+ /// the open pinned tab unloads and stays pinned, another pinned tab is archived.+ private func middleClickClose(_ id: UUID) {+ let group = sidebarUI.group(for: id, in: store)+ withAnimation(.snappy(duration: 0.22, extraBounce: 0)) {+ if group.count == 1, store.isPinned(id), selectedTabID != id {+ store.archiveTab(id, reason: .manual)+ } else {+ let open = selectedTabID+ for t in group.filter({ $0 != open }) + group.filter({ $0 == open }) { closeTab(t) }+ sidebarUI.multiSelection.subtract(group)+ }+ }}/// Two-finger swipes over the sidebar page between spaces the way Dia does@@ -1102,7 +1210,9 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMswitch event.phase {case .mayBegin, .began:let p = self.shell.convert(event.locationInWindow, from: nil)+ // The Library's lists don't page between spaces.let overSidebar = (self.shell.sidebarVisible || self.shell.floatingSidebar) && self.shell.sidebarHost.frame.contains(p)+ && self.sidebarUI.libraryPage == nilself.swipeAxis = overSidebar ? .undecided : .verticalself.swipeX = 0self.swipeY = 0@@ -1590,7 +1700,21 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM}func windowDidBecomeKey(_ notification: Notification) {- if (notification.object as? NSWindow) === window { shell.windowActive = true }+ guard (notification.object as? NSWindow) === window else { return }+ shell.windowActive = true+ reclaimPages()+ }++ func windowDidBecomeMain(_ notification: Notification) {+ guard (notification.object as? NSWindow) === window else { return }+ reclaimPages()+ }++ /// Back in this window: pages that moved to another window come back (Arc's untargeted+ /// reparenting). After AppDelegate has made this the active window.+ private func reclaimPages() {+ guard shell.paneCards.contains(where: \.showsElsewhere) else { return }+ DispatchQueue.main.async { [weak self] in self?.refresh() }}func windowDidResignKey(_ notification: Notification) {@@ -1637,9 +1761,10 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMisTornDown = truedismissTransientUI()browsers.closeAll()- for monitor in [scrollMonitor, childClickMonitor].compactMap({ $0 }) { NSEvent.removeMonitor(monitor) }+ for monitor in [scrollMonitor, childClickMonitor, middleClickMonitor].compactMap({ $0 }) { NSEvent.removeMonitor(monitor) }scrollMonitor = nilchildClickMonitor = nil+ middleClickMonitor = nilfloatingSidebar?.hide(animated: false)floatingSidebar = nilfor child in window?.childWindows ?? [] {@@ -1680,25 +1805,7 @@ final class CraWindow: NSWindow {/// here: a double-click runs the title bar action, anything else drags the window.private static let titleStripHeight = CraMetrics.contentInset + 4- /// Presses that belong to sidebar controls and must never drag the window (the space- /// dock). The sidebar's hover flag alone misses a pointer that left a control mid-drag- /// and jumped back in, so these are checked where the press lands.- var holdsPress: (NSPoint) -> Bool = { _ in false }- /// Movable-by-background once a held press ends.- var movableAfterPress: () -> Bool = { true }- private(set) var holdingPress = false-override func sendEvent(_ event: NSEvent) {- if event.type == .leftMouseDown, holdsPress(event.locationInWindow) {- holdingPress = true- isMovableByWindowBackground = false- }- defer {- if event.type == .leftMouseUp, holdingPress {- holdingPress = false- isMovableByWindowBackground = movableAfterPress()- }- }if event.type == .leftMouseDown, !styleMask.contains(.fullScreen),let content = contentView, event.locationInWindow.y >= content.bounds.height - Self.titleStripHeight,isTitleStrip(content.hitTest(content.convert(event.locationInWindow, from: nil))) {diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mmindex 1999cc1..bf25364 100644--- a/Sources/CraCEF/CraCEF.mm+++ b/Sources/CraCEF/CraCEF.mm@@ -8,6 +8,7 @@#include <crt_externs.h>#include <atomic>#include <map>+#include <set>#include <string>#include <vector>@@ -30,6 +31,7 @@#include "include/cef_request_context.h"#include "include/cef_request_handler.h"#include "include/cef_resource_request_handler.h"+#include "include/cef_urlrequest.h"#include "include/cef_version.h"#include "CraContentBlocker.h"#include "include/wrapper/cef_helpers.h"@@ -305,9 +307,23 @@ static void HideDownloadBubble(CefRefPtr<CefRequestContext> context) {}}+static bool g_httpsOnly = false;+static bool g_incognitoReady = false;++/// Chrome's "Always use secure connections" (Settings ▸ Privacy in Cra).+static void ApplyHttpsOnly(CefRefPtr<CefRequestContext> context) {+ CefRefPtr<CefValue> value = CefValue::Create();+ value->SetBool(g_httpsOnly);+ CefString error;+ if (!context->SetPreference("https_only_mode_enabled", value, error)) {+ NSLog(@"CraCEF: https_only_mode_enabled: %s", error.ToString().c_str());+ }+}+static void ApplyProfilePreferences(CefRefPtr<CefRequestContext> context) {ApplyWebRTCPolicy(context);HideDownloadBubble(context);+ ApplyHttpsOnly(context);}/// Profiles other than the global Default one get the same preferences once they load,@@ -317,7 +333,7 @@ public:explicit ProfileContextHandler(NSString* path = nil) : path_([path copy]) {}void OnRequestContextInitialized(CefRefPtr<CefRequestContext> context) override {ApplyProfilePreferences(context);- if (!path_) return;+ if (!path_) { g_incognitoReady = true; return; }if (!g_readyProfiles) g_readyProfiles = [NSMutableSet set];[g_readyProfiles addObject:path_];NSArray<CraBrowser*>* waiting = [g_waitingForProfile[path_] copy];@@ -492,6 +508,47 @@ private:IMPLEMENT_REFCOUNTING(FaviconCallback);};+// MARK: - Browser fetch++typedef void (^CraFetchCompletion)(NSInteger, NSString*, NSString*, NSString*);++/// Collects a CefURLRequest's body. Requests made on the UI thread call back on it.+class FetchClient : public CefURLRequestClient {+public:+ explicit FetchClient(CraFetchCompletion completion) : completion_([completion copy]) {}++ void OnDownloadData(CefRefPtr<CefURLRequest> request, const void* data, size_t length) override {+ body_.append(static_cast<const char*>(data), length);+ }+ void OnRequestComplete(CefRefPtr<CefURLRequest> request) override {+ CefRefPtr<CefResponse> response = request->GetResponse();+ bool ok = request->GetRequestStatus() == UR_SUCCESS && response;+ NSInteger status = ok ? response->GetStatus() : 0;+ NSString* finalURL = response ? NSStringFromCef(response->GetURL()) : @"";+ if (!finalURL.length) finalURL = NSStringFromCef(request->GetRequest()->GetURL());+ NSString* mime = response ? NSStringFromCef(response->GetMimeType()) : @"";+ NSString* body = [[NSString alloc] initWithBytes:body_.data() length:body_.size() encoding:NSUTF8StringEncoding] ?: @"";+ CraFetchCompletion done = completion_;+ completion_ = nil;+ CefRefPtr<CefURLRequest> finished = request;+ dispatch_async(dispatch_get_main_queue(), ^{+ InFlight().erase(finished);+ if (done) done(status, finalURL, mime, body);+ });+ }+ /// Requests stay referenced until they complete.+ static std::set<CefRefPtr<CefURLRequest>>& InFlight() { static std::set<CefRefPtr<CefURLRequest>> s; return s; }+ void OnUploadProgress(CefRefPtr<CefURLRequest> request, int64_t current, int64_t total) override {}+ void OnDownloadProgress(CefRefPtr<CefURLRequest> request, int64_t current, int64_t total) override {}+ bool GetAuthCredentials(bool isProxy, const CefString& host, int port, const CefString& realm, const CefString& scheme,+ CefRefPtr<CefAuthCallback> callback) override { return false; }++private:+ CraFetchCompletion completion_;+ std::string body_;+ IMPLEMENT_REFCOUNTING(FetchClient);+};+// MARK: - DevTools client// Diagnostic log for the DevTools life cycle: `defaults write dk.kildahl.cra devToolsLog -bool YES`,@@ -1769,6 +1826,18 @@ static void MarkProfileExitedCleanly(NSString* profileDir) {+ (void)setContentBlockingEnabled:(BOOL)enabled { cra_blocker::Enabled().store(enabled); }+ (BOOL)contentBlockingEnabled { return cra_blocker::Enabled().load(); }++/// Only contexts that finished loading take preferences (an uninitialised one is fatal);+/// the rest get it from ApplyProfilePreferences when they load.++ (void)setHttpsOnlyModeEnabled:(BOOL)enabled {+ g_httpsOnly = enabled;+ if (!g_contextInitialized) return;+ ApplyHttpsOnly(CefRequestContext::GetGlobalContext());+ for (auto& [path, context] : g_profileContexts) {+ if ([g_readyProfiles containsObject:@(path.c_str())]) ApplyHttpsOnly(context);+ }+ if (g_incognitoContext && g_incognitoReady) ApplyHttpsOnly(g_incognitoContext);+}+ (void)setBlockedDomains:(NSArray<NSString*>*)domains {auto* set = new cra_blocker::DomainSet();set->reserve(domains.count);@@ -1821,7 +1890,9 @@ static void MarkProfileExitedCleanly(NSString* profileDir) {CefMainArgs mainArgs(*_NSGetArgc(), *_NSGetArgv());CefSettings settings;- settings.no_sandbox = true;+ // Renderer, GPU and utility processes run in Chromium's seatbelt sandbox+ // (CraHelper enters it before loading the framework).+ settings.no_sandbox = false;CefString(&settings.cache_path) = CefStringFromNS(cachePath);CefString(&settings.root_cache_path) = CefStringFromNS(cachePath);settings.persist_session_cookies = true;@@ -1877,7 +1948,7 @@ static void MarkProfileExitedCleanly(NSString* profileDir) {}+ (NSInteger)liveBrowserCount { return g_liveBrowsers; }-+ (void)endIncognitoSession { g_incognitoContext = nullptr; }++ (void)endIncognitoSession { g_incognitoContext = nullptr; g_incognitoReady = false; }+ (NSString*)chromiumVersion {return [NSString stringWithFormat:@"%d.%d.%d.%d", CHROME_VERSION_MAJOR, CHROME_VERSION_MINOR,CHROME_VERSION_BUILD, CHROME_VERSION_PATCH];@@ -1891,6 +1962,34 @@ static void MarkProfileExitedCleanly(NSString* profileDir) {completion:(void (^)(NSString* _Nullable, NSString* _Nullable))completion {[self sendBrowserDevToolsMethod:method params:params sessionID:nil completion:completion];}++ (void)fetchURL:(NSString*)url headers:(NSDictionary<NSString*, NSString*>*)headers profilePath:(NSString*)profilePath+ completion:(void (^)(NSInteger, NSString*, NSString*, NSString*))completion {+ [self fetchURL:url headers:headers profilePath:profilePath attempt:0 completion:completion];+}++ (void)fetchURL:(NSString*)url headers:(NSDictionary<NSString*, NSString*>*)headers profilePath:(NSString*)profilePath+ attempt:(int)attempt completion:(void (^)(NSInteger, NSString*, NSString*, NSString*))completion {+ // Chromium's profiles load asynchronously; a fetch waits for its profile like a page does.+ BOOL ready = g_contextInitialized && (!profilePath.length || (ProfileContext(profilePath), [g_readyProfiles containsObject:profilePath]));+ if (!ready) {+ if (attempt >= 60) { completion(0, url, @"", @""); return; }+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ [self fetchURL:url headers:headers profilePath:profilePath attempt:attempt + 1 completion:completion];+ });+ return;+ }+ CefRefPtr<CefRequest> request = CefRequest::Create();+ request->SetURL(CefStringFromNS(url));+ request->SetMethod("GET");+ // Sent like the page's own navigation: stored cookies, first party = the site itself.+ request->SetFlags(UR_FLAG_ALLOW_STORED_CREDENTIALS | UR_FLAG_SKIP_CACHE);+ request->SetFirstPartyForCookies(CefStringFromNS(url));+ CefRequest::HeaderMap map;+ for (NSString* name in headers) map.insert({CefStringFromNS(name), CefStringFromNS(headers[name])});+ request->SetHeaderMap(map);+ CefRefPtr<CefRequestContext> context = profilePath.length ? ProfileContext(profilePath) : CefRequestContext::GetGlobalContext();+ CefRefPtr<CefURLRequest> r = CefURLRequest::Create(request, new FetchClient(completion), context);+ if (r) FetchClient::InFlight().insert(r); else completion(0, url, @"", @"");+}+ (void)sendBrowserDevToolsMethod:(NSString*)method params:(NSString*)params sessionID:(NSString*)sessionIDcompletion:(void (^)(NSString* _Nullable, NSString* _Nullable))completion {if (g_cdpWriteFD < 0) { completion(nil, @"no DevTools pipe"); return; }diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.hindex 5a9ff7e..952457f 100644--- a/Sources/CraCEF/include/CraCEF.h+++ b/Sources/CraCEF/include/CraCEF.h@@ -182,6 +182,10 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {/// the next request, any time, from any thread. Off until enabled.+ (void)setContentBlockingEnabled:(BOOL)enabled;+ (BOOL)contentBlockingEnabled;+/// Chrome's HTTPS-Only Mode ("Always use secure connections") in every profile:+/// http:// navigations are upgraded, and a site without HTTPS shows Chrome's warning+/// page before it loads. Profiles that load later get it too. Off until enabled.++ (void)setHttpsOnlyModeEnabled:(BOOL)enabled;/// Replaces the blocked list (bare domains; a domain also covers its subdomains).+ (void)setBlockedDomains:(NSArray<NSString *> *)domains;/// Reads and installs a list file off the main thread: one domain per line or@@ -227,6 +231,13 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {/// Browser-level DevTools protocol call (Target.*, Extensions.*) over the private pipe.+ (void)sendBrowserDevToolsMethod:(NSString *)method params:(NSString *)paramscompletion:(void (^)(NSString * _Nullable result, NSString * _Nullable error))completion;+/// A GET made by the browser itself with a profile's cookies (nil is Default), as a+/// page of that profile would make it: how Arc's and Dia's live folders read github.com+/// with the user's own session. The completion gets the HTTP status (0 when the request+/// failed), the URL after redirects, the MIME type and the body as UTF-8, on the main queue.++ (void)fetchURL:(NSString *)url headers:(nullable NSDictionary<NSString *, NSString *> *)headers+ profilePath:(nullable NSString *)profilePath+ completion:(void (^)(NSInteger status, NSString *finalURL, NSString *mimeType, NSString *body))completion;/// Same, inside an attached target's session (Target.attachToTarget with flatten).+ (void)sendBrowserDevToolsMethod:(NSString *)method params:(NSString *)params sessionID:(nullable NSString *)sessionIDcompletion:(void (^)(NSString * _Nullable result, NSString * _Nullable error))completion;diff --git a/Sources/CraHelper/main.cc b/Sources/CraHelper/main.ccindex 31b21be..1b383fc 100644--- a/Sources/CraHelper/main.cc+++ b/Sources/CraHelper/main.cc@@ -1,10 +1,17 @@// Entry point for every Chromium subprocess (renderer, GPU, utility, plugin,-// alerts). Loads the framework from the enclosing Cra.app bundle and hands-// control to CEF.+// alerts). Enters the macOS sandbox, then loads the framework from the+// enclosing Cra.app bundle and hands control to CEF.#include "include/cef_app.h"+#include "include/cef_sandbox_mac.h"#include "include/wrapper/cef_library_loader.h"int main(int argc, char* argv[]) {+ // The seatbelt profile has to be in place before the framework loads.+ // libcef_sandbox.dylib ships inside the framework (Libraries/).+ CefScopedSandboxContext sandbox_context;+ if (!sandbox_context.Initialize(argc, argv)) {+ return 1;+ }CefScopedLibraryLoader library_loader;if (!library_loader.LoadInHelper()) {return 1;diff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.mdindex f2c99f2..914c29d 100644--- a/docs/arc-reverse-engineering.md+++ b/docs/arc-reverse-engineering.md@@ -761,7 +761,7 @@ of the sidebar strip, pixel runs at x=500 px (2x), y = 160/700/1200/1700/2100.taking synthetic input before that test finished.- [?] Arc's pinned-tab context-menu titles (short Swift literals are inline in code, not in `strings`).- Cra (TabRow): current pinned → `minus`, "Close and Keep Pinned (⌘W)", unload + reset + select the- most recently active tab (`SidebarStore.mostRecentTab`); other pinned → ✕, "Archive this tab",+ most recently active tab that is still open (closed pinned tabs are skipped, else two of them ping-pong); other pinned → ✕, "Archive this tab",`archiveTab`. Context menu: "Close and Keep Pinned" (only when open/loaded) and "Archive Tab". The URLtooltip moved from the row to the title so the buttons' tooltips show. No attention ring yet.- Tooltips on these buttons (ArcTooltip module, field metadata): `ArcTooltipConfiguration { content,@@ -1506,9 +1506,63 @@ strings "Opens the tab switcher, where you can cycle through recent tabs like Co- [U] Arc's hover fill could not be recorded (live pointer runs were cut short while Victor was at the Mac); the pressedvalue is used for hover too, and the light-theme fill (black 5%) is a guess. Arc's drag image follows the pointerfreely (system drag session); Cra keeps the dragged icon on the dock's row.-- Cra: `SpaceDock` uses 34×32 contiguous cells with one `DragGesture` per cell: fill on hover and press, release inside- the cell switches space, a horizontal drag reorders (neighbours slide a cell aside, the icon settles, then- `moveSpace`). `CraWindow.holdsPress` turns movable-by-background off for any press inside the strip until mouse-up,- because the hover flag (`hoverDraggable`) missed a pointer that left the strip mid-drag and jumped back in. Verified- on a renamed test bundle: presses, shaky clicks and drags in the strip never move the window; a drag on empty- sidebar background still does.+- Cra: `SpaceDock` draws 34×32 contiguous cells in SwiftUI; an AppKit view over the strip (`SpaceDockMouse`) takes+ the mouse like Arc's item view: `mouseDownCanMoveWindow` false (a press there never moves the window), hover from+ its own tracking area, click on mouse-up inside the pressed cell, horizontal drag reorders (neighbours slide a cell+ aside, the icon settles, then `moveSpace`), right-click menu via `menu(for:)`. 0.1.13 used a SwiftUI+ `DragGesture(minimumDistance: 0)` per cell plus a `CraWindow` press guard instead; that dropped every other click+ (the window got the press, the gesture never began), so spaces needed a double click. Verified on a renamed test+ bundle with real HID clicks: five clicks in a row each switch, a shaky click switches, a release off the cell+ doesn't, a reorder is saved, the window never moves from the strip, and a drag on empty sidebar background does.++## Library (Arc 1.170, 27 Oct 2026, AX tree + window captures + 60 fps app-only recording + Swift metadata)++GitHub issue #3: Cra's Library was a separate window, so a click elsewhere sent it behind the browser, and the+Library button's hover list (downloads) and its click (the archive) showed different things.++- [O static] Arc's Library is window state, not a window: `Browser/Windows/Store/WindowState+Library.swift`, pages in+ `HomeButton/Pages/{Archive,Downloads,Media,…}`, a `HomeButton.HomeViewController` with `PageSidebarItem`s. The Library+ button is `SidebarHomeButton` (AX description "Home"). `LibraryOpenSource` = keyboardShortcut / iconTap / swipe,+ `LibraryCloseSource` = keyboardShortcut / escape / iconTap / swipe: nothing closes it on a click elsewhere.+ Window menu: View Library, View Downloads ("Opens the Downloads section of your Library."), View Easels & Notes,+ View Media, View Boosts.+- [O AX + capture, 1728×1084 window, 347 pt sidebar] the Library replaces the whole sidebar and widens it to 417 pt:+ a 113 pt page rail and the page's list. Rail buttons (AXButton, description = page name) 97×80 at x 8, 100 pt+ apart (Media 280, Downloads 380, … Archived Tabs 780 in screen y; window top 33), the group centred vertically.+ Glyph 18 pt tall from 22 pt into the button, label 12 pt semibold (white 60 %, ~82 % when chosen). The chosen page+ gets a white ~7 % fill (33,33,49 over 18,18,36) and its glyph filled in the space's accent (38,47,245 in Victor's+ JYSK theme). The rail carries a faint white wash rising toward its right edge and a 1 pt hairline (33,31,47) at+ x 112; the list sits on the plain sidebar colour.+- [O] list column: search field 36 pt tall from x 120 to 332, 10 pt below the window top ("Search Archive…",+ "Search Downloads…"), Filter button 73×36 at x 336; day headers ("Today", 13 pt semibold, x 124); rows 56 pt apart:+ 24 pt icon tile at x 130, title at x 164 in 14 pt, URL under it in 12 pt. Empty Downloads page: a download glyph,+ "Nothing here yet!", "Come back after you've found some cool stuff to save."+- [O] bottom: a back arrow (32×32 at x 8, 8 pt above the bottom) leaves the Library; a gift button at x 73.+- [O] reopening shows the page last used (left on Archived Tabs, reopened on Archived Tabs).+- [O 60 fps] opening: the Library is in place within 2–3 frames, sliding in from a little to the left. Closing: it+ slides left and fades while the tab list fades back in, ~6 frames, the card edge easing from 417 to 347.+- [U] Whether the list column keeps a fixed 304 pt or follows the sidebar width (both give 417 pt at 347); Cra adds+ 70 pt to the user's width. The open animation's exact curve.+- Cra: `LibraryView` in the sidebar (Downloads and Archived Tabs; Cra has no Media, Easels, Spaces or Boosts pages),+ `SidebarUIState.libraryPage` per window, `MainWindowController.showLibrary/closeLibrary`. The Library button and+ ⇧⌘L toggle it on the last page, ⇧⌘J opens Downloads, "View Archive" opens Archived Tabs, Esc and the back arrow+ leave. Opening it from a hidden sidebar shows the sidebar until it closes.++## A tab open in two windows (Arc 1.170, 27 Oct 2026, Swift metadata)++GitHub issue #4: opening in window B a tab that window A shows left A with no tab selected.++- [O static] Arc moves the page ("reparenting", `SharedWindowFeature/WindowData+ContentReparenting.swift`,+ `reparentWindowContent(for:from:to:trigger:)`, `ReparentingTrigger` = targeted / untargeted,+ `ReparentingMode` = shallow / deep, feature flags `global-window-content-reparenting-enabled` and+ `reparented-window-content-placeholders-enabled`). The window that lost the page keeps a placeholder:+ `ContentPlaceholderClient` (registerPlaceholder, placeholderSnapshots; `Placeholder` has data and sidebarItemID),+ `ContentSnapshotClient`, `BlurredItemContent` (item, image, colorScheme), `BlurredSnapshotView`, a+ "BlurredBackground" colour asset.+- [U] not observed live (two Arc windows need keyboard focus): the blur radius, whether text sits on the+ placeholder, and exactly when the untargeted reparent fires.+- Cra: both windows keep the tab selected (SidebarStore no longer clears the other window's selection). The window+ in use holds the page; another window that has the tab open shows a blurred copy of its last snapshot+ (`PaneCardView.elsewhereSnapshot`, the tab switcher's thumbnail) and takes the page back when it becomes key or+ main. Windows restored at launch leave the page to the window in use, else the first one. Verified on a renamed+ test bundle with two windows on the same tab: page and blur swap each time the other window becomes main.diff --git a/docs/live-folders.md b/docs/live-folders.mdnew file mode 100644index 0000000..84e470f--- /dev/null+++ b/docs/live-folders.md@@ -0,0 +1,114 @@+# Live folders (GitHub pull requests)++How Arc and Dia build their GitHub live folders, and how Cra mirrors them.+Targets: Arc 1.170.0 (/Applications/Arc.app), Dia 1.54.2 (/Applications/Dia.app), 27 Oct 2026.+Method: `strings` on both executables, Arc's own data files in ~/Library/Application Support/Arc,+Arc's AX tree and screen captures of its real "Pull Requests" folder, and GitHub's responses to+Cra's own requests. No decompiler on this Mac, so no control flow was read.++Legend: [O] observed, [I] inference, [U] unknown.++## Where the code lives in Arc and Dia+- [O] Both ship the same client, `Frameworks/ARCClients/Sources/GitHubClient/GitHubClient.swift`+ and `GitHubClient+PullRequestsParsing.swift`. Arc's folder model is `LiveFoldersFeature/StorableLiveData.swift`.+ Dia's is `BoostBrowser/Sources/LiveFolders/` (`LiveFolderManager`, `LiveFolderController`,+ `GitHubLiveFolderDataSource`, `PullRequestsLiveFolderDataSource`, `BitbucketLiveFolderDataSource`,+ `LiveDataRefreshSource`). Dia also has Documents, Chats, Notion, Drive and Confluence sources and keeps+ live folders in SQLite (`live_folders`, column `data_source_config`).+- [O] No OAuth app and no token. The client reads github.com with the browser's own session: error cases+ "Not signed in to GitHub", "GitHub SSO required", "Rate Limit Exceeded", "Requested too soon",+ "Unexpected GitHub page structure", "Missing Webcontents for PR". Request headers in the binary:+ `GitHub-Verified-Fetch`, `X-Requested-With`. Sign-in URLs it watches: github.com/login, /logout, /sessions/two-factor/*.+- [O] Pages it reads: `https://github.com/pulls` plus a search (`Failed to construct search URL`, `PR search failed`).+ JSON keys `pullsDashboardSurfaceContentRoute`, `pullsDashboardSurfaceLayoutRoute`, `repoNameWithOwner`,+ `requestingMyReview`, `createdByMe`; it checks for `app-name="dashboard-surface"` (GitHub's React dashboard)+ and falls back to XPath over the classic list (`.js-active-navigation-container > div`,+ `a[@data-hovercard-type='pull_request']`, `a[@data-hovercard-type='repository']`, octicon-git-pull-request*).+- [O] Dia's search terms: `is:pr is:open author:@me`, `user-review-requested:@me`, `review-requested:@me`,+ `review:approved involves:@me`, `review:changes_requested involves:@me`, `sort:updated-desc`, `updated:>=`.+- [O] Single pull request pages are read by running a script in a page (the JS that collects `.gh-header`,+ `relative-time`, diff stats, conflicts, unresolved conversations). Cra doesn't need it for the folder.+- [O] SSO: links to `/orgs/<org>/sso`, `global-sso-banner`, `sso_organizations`; Arc copy "SSO ensures all of your+ organizations' PRs appear", "Login with SSO to unlock this folder".++## Arc's stored model (Victor's real folder)+- [O] StorableSidebar.json, a `list` item titled "Pull Requests" in the JYSK space's pinned container:+ `automaticLiveFolderData { dataSource: {github: {}}, filter: {github: {attributes: 7, hiddenRepositories:+ [{owner, name, provider}]}}, hiddenItems: [{url}], lastFetch: {timestamp, status: {success}} }`,+ `customInfo.iconType.icon = "github"`.+- [O] Its children are ordinary tabs with `liveItemID.url` = the pull request URL; `savedTitle` is the pull+ request's title (not the page title), new ones arrive `isUnread: true`, a tab's `createdAt` is the pull+ request's creation time, children are newest first.+- [O] `hiddenItems` holds pull requests that are still open and awaiting review but no longer in the folder:+ closing a tab out of the folder keeps it out.+- [O] StorableLiveData.json caches each item: `github.pullRequest {author, number, repo{owner,name,provider},+ title, status {open|merged: date}, reviewStatus, isAwaitingMyReview, createdByMe, hasKnownStackMembership, updatedAt}`.+- [I] `attributes` bits: 1 = authored, 2 = review requests to you, 4 = team review requests ("Team Review+ Requests" is a string beside `hiddenRepositories`; 7 = all three, matching Dia's three queries).+- [U] Arc's refresh interval: it reads `automatic-live-folders-min-refresh-interval-in-seconds` from a remote+ flag whose value isn't cached on this Mac.++## Dia's refresh timing+- [O] Dia's LaunchDarkly cache (~/Library/Preferences/com.launchdarkly.client.X35+6+…plist, 27 Oct 2026):+ `github-live-folder-min-refresh-interval-seconds` 120, `github-live-folder-post-merge-retention-seconds` 120,+ `github-live-folder-post-review-retention-seconds` 120, `github-live-folder-json-api-enabled` true,+ `github-live-folder-realtime-updates-enabled` true, `github-live-folder-edit-creation-trigger-enabled` true,+ `github-live-folder-review-creation-trigger-enabled` true, `live-data-proactive-fetching` false.+- [O] Refresh reasons: periodicRefresh, windowFocus, manualRefresh, configChanged, tabReinserted, tabAdopted,+ externalTrigger. The refresh controller keeps `nextEligibleRefreshAt` and skips with rateLimited,+ sourceUnavailable, waitingForActiveWindow. The client has fetchPullRequests, readCurrentUserLogin,+ fetchPullRequestChecks, subscribeToRealtimeUpdates, subscribeToPullRequestDescriptionEditTrigger;+ `reparentPullRequestTabToLiveFolder(url:…createdByMe:)` moves a pull request tab you open into the folder.+- [I] At most one GitHub refresh per 120 s, only while a Dia window is active, plus refreshes when a window+ gains focus and when you create, edit or review a pull request in a tab. Merged and reviewed pull requests+ stay 120 s before they leave the folder.+- [I] How the realtime updates arrive: the signed-in pulls JSON gives each pull request an `aliveChannel` and a+ `commitHeadShaChannel` (null in the responses seen), the names of GitHub's live-update socket channels.+ Dia probably subscribes to those; no socket code was found in its strings, so this is unconfirmed.++## Arc's folder on screen (captured 27 Oct)+- [O] Folder row: Arc's usual folder glyph in the space's folder colours with GitHub's mark on its front;+ title bold like other folders. A 26×26 trailing button showed a ⚠ that stayed on hover (the folder was in+ an error state; the healthy state's button was not seen).+- [O] Pull request rows: GitHub mark as the icon, author login under the title for other people's pull+ requests (`sidebarItemSubtitleTextField`), none under your own; unread dot; ✕ on hover like any pinned tab.+- [O] Context menu strings: "Copy All Links as Markdown", "Delete Live Folder", repository list explained by+ "This list is generated based on your currently active pull requests.", "Failed to update". Deleting asks+ "Delete your %@ Live Folder?". Not in Arc's menu bar (only a debug menu "Automatic Live Folders").++## What Cra does+- Fetch: `+[CraCEFRuntime fetchURL:headers:profilePath:completion:]`, a browser-side `CefURLRequest` on the+ space's profile, so it carries that profile's cookies. GitHubLiveClient runs one search per enabled+ filter: `/pulls?q=…` with the JSON headers first, `/search?type=pullrequests` when that gives nothing it+ can read. The reader accepts GitHub's JSON routes, embedded React data and the classic list.+- Folder: `SidebarItem.liveFolder` (LiveFolderData), tabs carry `liveItemURL` and `liveSubtitle`.+ SidebarStore.applyLiveResults adds and updates tabs, moves a Today tab already on a new pull request into+ the folder, and marks ones that left the results (`liveGoneAt`); `expireLiveItems` removes them 120 s later+ (a tab open in a window stays until it isn't). Closing or dragging a tab out adds it to `hiddenItems`.+ Nothing can be dropped into a live folder.+- Refresh, on Dia's schedule: at most every 120 s and only while Cra is the active app; when any Cra window+ becomes key; from the folder's button and menu (10 s apart); forced when a filter changes; forced 5 s and+ 45 s after a tab goes from a repository's compare page to a pull request (one was just created) or to a+ `#pullrequestreview-` anchor (a review was submitted). One GitHub folder per space ("New GitHub Live+ Folder" in the sidebar menus and command bar). Not copied: Dia's realtime updates (see below).++## Verified (27 Oct 2026)+- GitHub's answers when signed out: `/pulls` with the JSON headers returns 404 `{"error":"Couldn’t authenticate you"}`;+ `/search?type=pullrequests` returns 200 JSON `payload.blackbirdSearchRoute` with `"logged_in":false`. Both+ read as "not signed in"; the test instance showed "Sign back in to GitHub." and the warning button.+- Real search results (cli/cli, via a scratch build that swapped the `@me` terms for a public query):+ `results[]` with `number`, `hl_title`, `author_name`, `state` open|draft, `merged`, `created`+ (with UTC offsets), `repo.repository.{owner_login,name}`, `issue.issue.pull_request_id`. All ten parsed;+ the folder filled, a removed item came back unread, closing one kept it out across a refresh.+- The browser-side request sends both SameSite=Lax and SameSite=Strict cookies of the profile (checked+ against httpbin.org/cookies), so GitHub's `user_session` and `__Host-user_session_same_site` go along.+- Signed in (Victor's account in a test profile, after JYSK SSO): `/pulls` with the JSON headers returns+ 200 `payload.pullsDashboardSurfaceContentRoute {results[], pageInfo, error}`; each result has `number`,+ `title`, `permalink`, `repoNameWithOwner`, `author {displayLogin, displayName}`, `state` OPEN, `isDraft`,+ `mergedAt`, `createdAt`, `updatedAt`, `aliveChannel`. Six pull requests filled the folder from it, without the+ search fallback. Authors come from `displayLogin` (missed at first, fixed).+- Schedule (scratch build with public queries): the compare → pull request trigger refreshed at once and again+ 45 s later; items that left the results were kept, then removed after 120 s; an open Today tab on a returning+ pull request was moved into the folder without a duplicate; no fetch for 2.5 minutes in the background,+ one within a second of the window taking focus.+- Not verified: the review trigger (`#pullrequestreview-` anchor) with a real review.diff --git a/docs/release.md b/docs/release.mdindex f858df1..a469b40 100644--- a/docs/release.md+++ b/docs/release.md@@ -126,6 +126,11 @@ The entitlements are the hardened-runtime exceptions Chromium needs (JIT, unsignexecutable memory, library validation off, dyld environment variables), plus camera,microphone and location so sites can ask for them.+The helpers run in Chromium's own macOS sandbox (seatbelt): `CraHelper` enters it through+`CefScopedSandboxContext` (which loads the framework's `Libraries/libcef_sandbox.dylib`)+before loading CEF, and `CefSettings.no_sandbox` is off. Renderer, GPU, network, storage+and audio processes are sandboxed, video capture is not (Chrome's choice too).+## PasskeysSecurity keys and phones (the QR code in Chrome's "Passkeys & Security Keys" dialog)diff --git a/scripts/cef-patches/extension-popup-browser-info.patch b/scripts/cef-patches/extension-popup-browser-info.patchnew file mode 100644index 0000000..0a05df1--- /dev/null+++ b/scripts/cef-patches/extension-popup-browser-info.patch@@ -0,0 +1,28 @@+diff --git a/cef/libcef/browser/browser_info_manager.cc b/cef/libcef/browser/browser_info_manager.cc+index 8b077f0..ff7fc60 100644+--- a/cef/libcef/browser/browser_info_manager.cc++++ b/cef/libcef/browser/browser_info_manager.cc+@@ -26,6 +26,8 @@+ #include "content/public/browser/web_ui.h"+ #include "content/public/browser/web_ui_controller.h"+ #include "content/public/common/url_constants.h"++#include "extensions/browser/view_type_utils.h"++#include "extensions/common/mojom/view_type.mojom.h"++ namespace {++@@ -650,6 +652,14 @@ bool CefBrowserInfoManager::IsExcludedFrameHost(content::RenderFrameHost* rfh) {+ return true;+ }+++ // Cra: a Chrome-style extension popup (ExtensionPopup's ExtensionViewHost) has++ // no CefBrowser, so its renderer otherwise waits out the 2 s new browser info++ // timeout before the popup page loads.++ if (extensions::GetViewType(web_contents) ==++ extensions::mojom::ViewType::kExtensionPopup) {++ return true;++ }+++ return false;+ }+diff --git a/scripts/fetch-cef.sh b/scripts/fetch-cef.shindex 5188e67..d6d0d2f 100755--- a/scripts/fetch-cef.sh+++ b/scripts/fetch-cef.sh@@ -38,7 +38,7 @@ fiif [ ! -f vendor/cef/build/libcef_dll_wrapper/libcef_dll_wrapper.a ]; thenecho "Building libcef_dll_wrapper..."cmake -S vendor/cef -B vendor/cef/build -G "Unix Makefiles" \- -DCMAKE_BUILD_TYPE=Release -DPROJECT_ARCH=arm64 -DUSE_SANDBOX=OFF \+ -DCMAKE_BUILD_TYPE=Release -DPROJECT_ARCH=arm64 -DUSE_SANDBOX=ON \-DCMAKE_OSX_ARCHITECTURES=arm64 > vendor/cef/build-configure.logcmake --build vendor/cef/build --target libcef_dll_wrapper -j "$(sysctl -n hw.ncpu)" > vendor/cef/build-wrapper.logfi