The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.
⌃Tab leaves out closed pinned tabs, Return on a completing tab switches to it, Chrome's Delete browsing data clears the command bar, and covered windows send their video to Picture in Picture (#117)
Victor Kildahl342472943d09
diff --git a/Packages/CraCore/Sources/CraCore/BrowsingDataClear.swift b/Packages/CraCore/Sources/CraCore/BrowsingDataClear.swiftnew file mode 100644index 0000000..2a3e878--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/BrowsingDataClear.swift@@ -0,0 +1,75 @@+import Foundation++/// Arc's Clear Browsing Data (Settings ▸ Profiles) opens Chrome's settings at Privacy and security,+/// where "Delete browsing data" is Chrome's dialog. Arc's command bar reads Chromium's history, so+/// what the dialog deletes leaves it (Arc 1.171, offline copy, 2 Nov 2026: after "Last 7 days" the+/// command bar listed no history for the deleted pages). Cra's command bar reads its own history+/// (history.json) and learned picks (commandbar.json), which follow the dialog: its delete sends+/// `chrome.send("clearBrowsingData", [callback, data types, time period])` (Chromium 156,+/// settings_clear_browsing_data_handler.cc), which Cra hears on the page. Reported on X,+/// 1 Nov 2026: cleared history kept showing in the command bar.+public enum BrowsingDataClear {+ public static let pageURL = "chrome://settings/clearBrowserData"+ /// browsing_data::prefs::kDeleteBrowsingHistory.+ public static let historyDataType = "browser.clear_data.browsing_history"++ public enum Range: Equatable {+ case allTime+ /// Visited at or after the date.+ case since(Date)+ /// Visited before the date.+ case before(Date)++ public func contains(_ date: Date) -> Bool {+ switch self {+ case .allTime: return true+ case .since(let d): return date >= d+ case .before(let d): return date < d+ }+ }+ }++ /// The history the dialog deletes, or nil when history isn't among what it deletes.+ /// `timePeriod` is browsing_data::TimePeriod.+ public static func historyRange(dataTypes: [String], timePeriod: Int, now: Date) -> Range? {+ guard dataTypes.contains(historyDataType) else { return nil }+ let day: TimeInterval = 86400+ switch timePeriod {+ case 0: return .since(now.addingTimeInterval(-3600)) // LAST_HOUR+ case 1: return .since(now.addingTimeInterval(-day)) // LAST_DAY+ case 2: return .since(now.addingTimeInterval(-7 * day)) // LAST_WEEK+ case 3: return .since(now.addingTimeInterval(-28 * day)) // FOUR_WEEKS+ case 4: return .allTime // ALL_TIME+ case 5: return .before(now.addingTimeInterval(-30 * day)) // OLDER_THAN_30_DAYS+ case 6: return .since(now.addingTimeInterval(-15 * 60)) // LAST_15_MINUTES+ default: return nil+ }+ }++ /// The message's arguments after the callback id, as the page hands them over (JSON).+ public static func historyRange(messageJSON: String, now: Date) -> Range? {+ guard let data = messageJSON.data(using: .utf8),+ let args = try? JSONSerialization.jsonObject(with: data) as? [Any], args.count == 2,+ let types = args[0] as? [String], let period = args[1] as? Int else { return nil }+ return historyRange(dataTypes: types, timePeriod: period, now: now)+ }++ /// History and learned signals without `range`. Cra keeps a page's last visit only, so a+ /// page last visited inside the range goes with all its visits. Learned picks of pages that+ /// went go too, all of them for all time, and so do tab switches inside the range.+ public static func clearing(_ range: Range, history: [String: HistoryEntry],+ ranking: RankingData) -> (history: [String: HistoryEntry], ranking: RankingData) {+ let kept = history.filter { !range.contains($0.value.lastVisit) }+ var r = ranking+ if range == .allTime {+ r.queriesToSelected = [:]+ } else {+ let gone = Set(history.keys).subtracting(kept.keys)+ r.queriesToSelected = r.queriesToSelected.filter { !gone.contains($0.value) }+ }+ r.recentlySwitchedToTabs = r.recentlySwitchedToTabs+ .mapValues { $0.filter { !range.contains($0) } }+ .filter { !$0.value.isEmpty }+ return (kept, r)+ }+}diff --git a/Packages/CraCore/Sources/CraCore/CommandBarDedupe.swift b/Packages/CraCore/Sources/CraCore/CommandBarDedupe.swiftnew file mode 100644index 0000000..b8ced11--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/CommandBarDedupe.swift@@ -0,0 +1,92 @@+import Foundation++/// The command bar lists a page once. Rows name the same page when their addresses match without+/// `www.` and a trailing slash, or, for sites whose pages share titles, when host and title match+/// (Arc's dedupByTitleAndHostList). Of such rows the open tab's stays, so Return switches to the+/// tab instead of opening the page again, and it lists with the best score among them. Reported+/// on X, 1 Nov 2026: a pinned YouTube tab lost its row to a YouTube history entry that had more+/// visits, and Return opened a new tab. Arc 1.171, offline copy with injected history, 2 Nov 2026:+/// "semrush" listed the pinned tab at www.semrush.com/projects/ and hid the history entries for+/// semrush.com/projects/ and www.semrush.com/projects (more visits, other titles), while+/// www.semrush.com/analytics/ stayed.+public enum CommandBarDedupe {+ /// Arc's command_bar_behavior.json: dedupByTitleAndHostList.+ public static let titleAndHostHosts: Set<String> = [+ "figma.com", "www.figma.com", "notion.so", "www.notion.so", "github.com", "zoom.us", "maps.google.com",+ "console.cloud.google.com", "app.slack.com", "linear.app", "www.youtube.com", "docs.google.com", "mail.google.com",+ ]++ /// The address rows are compared by: no `www.`, no trailing slash, the host lowercased.+ public static func comparableURL(_ url: String) -> String {+ guard var c = URLComponents(string: url), let host = c.host?.lowercased() else { return url }+ c.host = host.hasPrefix("www.") ? String(host.dropFirst(4)) : host+ if c.path.hasSuffix("/") { c.path.removeLast() }+ return c.string ?? url+ }++ /// What an open tab completes the typed text to (Arc): its address without the scheme,+ /// `www.` and a trailing slash, "semrush.com/projects".+ public static func completionAddress(_ url: String) -> String {+ var s = comparableURL(url)+ if let r = s.range(of: "://") { s = String(s[r.upperBound...]) }+ return s+ }++ /// The keys a row matches others by. Commands and rows without an address keep their `id`.+ public static func keys(id: String, url: String?, title: String) -> [String] {+ guard let url, let host = URL(string: url)?.host?.lowercased() else { return [id] }+ let page = comparableURL(url)+ return titleAndHostHosts.contains(host) ? [page, "\(host)|\(title.lowercased())"] : [page]+ }++ public struct Row: Equatable {+ public let keys: [String]+ public let score: Double+ public let isOpenTab: Bool++ public init(keys: [String], score: Double, isOpenTab: Bool) {+ self.keys = keys+ self.score = score+ self.isOpenTab = isOpenTab+ }+ }++ /// The rows kept, as indices into `rows` with the score each lists with, best first (rows+ /// with equal scores in the order given). Rows sharing any key are one page.+ public static func kept(_ rows: [Row]) -> [(index: Int, score: Double)] {+ // Union rows that share a key; the group's root is its first row.+ var parent = Array(rows.indices)+ func root(_ i: Int) -> Int {+ var i = i+ while parent[i] != i { parent[i] = parent[parent[i]]; i = parent[i] }+ return i+ }+ var byKey: [String: Int] = [:]+ for (i, row) in rows.enumerated() {+ for k in row.keys {+ if let j = byKey[k] {+ let (a, b) = (root(i), root(j))+ if a != b { parent[max(a, b)] = min(a, b) }+ } else {+ byKey[k] = i+ }+ }+ }+ var best: [Int: (index: Int, score: Double)] = [:]+ var order: [Int] = []+ for (i, row) in rows.enumerated() {+ let g = root(i)+ guard let held = best[g] else {+ best[g] = (i, row.score)+ order.append(g)+ continue+ }+ let current = rows[held.index]+ let wins = row.isOpenTab != current.isOpenTab ? row.isOpenTab : row.score > current.score+ best[g] = (wins ? i : held.index, max(held.score, row.score))+ }+ return order.enumerated().map { (offset: $0.offset, kept: best[$0.element]!) }+ .sorted { a, b in a.kept.score != b.kept.score ? a.kept.score > b.kept.score : a.offset < b.offset }+ .map(\.kept)+ }+}diff --git a/Packages/CraCore/Tests/CraCoreTests/BrowsingDataClearTests.swift b/Packages/CraCore/Tests/CraCoreTests/BrowsingDataClearTests.swiftnew file mode 100644index 0000000..232f2b7--- /dev/null+++ b/Packages/CraCore/Tests/CraCoreTests/BrowsingDataClearTests.swift@@ -0,0 +1,66 @@+import CraCore+import Foundation+import Testing++/// Chrome's Delete browsing data dialog also clears the command bar's history.+struct BrowsingDataClearTests {+ let now = Date(timeIntervalSinceReferenceDate: 800_000_000)+ let history = BrowsingDataClear.historyDataType++ static let periods: [(Int, Double)] = [(6, 900), (0, 3600), (1, 86400), (2, 604_800), (3, 2_419_200)]++ @Test(arguments: periods)+ func recentPeriods(period: Int, seconds: Double) {+ #expect(BrowsingDataClear.historyRange(dataTypes: [history], timePeriod: period, now: now) == .since(now.addingTimeInterval(-seconds)))+ }++ @Test func allTimeAndOlderThan30Days() {+ #expect(BrowsingDataClear.historyRange(dataTypes: [history], timePeriod: 4, now: now) == .allTime)+ #expect(BrowsingDataClear.historyRange(dataTypes: [history], timePeriod: 5, now: now) == .before(now.addingTimeInterval(-30 * 86400)))+ #expect(BrowsingDataClear.historyRange(dataTypes: [history], timePeriod: 99, now: now) == nil)+ }++ /// Only cookies and cache: the command bar keeps its history.+ @Test func historyNotTicked() {+ #expect(BrowsingDataClear.historyRange(dataTypes: ["browser.clear_data.cookies", "browser.clear_data.cache"], timePeriod: 4, now: now) == nil)+ }++ /// What the page hands over: the message's arguments after the callback id.+ @Test func fromTheMessage() {+ let json = #"[["browser.clear_data.browsing_history","browser.clear_data.cookies"],1]"#+ #expect(BrowsingDataClear.historyRange(messageJSON: json, now: now) == .since(now.addingTimeInterval(-86400)))+ #expect(BrowsingDataClear.historyRange(messageJSON: #"[["browser.clear_data.cache"],4]"#, now: now) == nil)+ #expect(BrowsingDataClear.historyRange(messageJSON: "null", now: now) == nil)+ #expect(BrowsingDataClear.historyRange(messageJSON: #"[[],"x"]"#, now: now) == nil)+ }++ @Test func lastHourDropsWhatWasVisitedInIt() {+ let old = HistoryEntry(url: "https://old.example/", title: "Old", lastVisit: now.addingTimeInterval(-7200), visitCount: 3)+ let new = HistoryEntry(url: "https://new.example/", title: "New", lastVisit: now.addingTimeInterval(-60), visitCount: 1)+ let tab = UUID()+ let ranking = RankingData(recentlySwitchedToTabs: [tab: [now.addingTimeInterval(-7200), now.addingTimeInterval(-60)], UUID(): [now]],+ queriesToSelected: ["old": old.url, "new": new.url], commandUsage: ["settings": 2])+ let out = BrowsingDataClear.clearing(.since(now.addingTimeInterval(-3600)), history: [old.url: old, new.url: new], ranking: ranking)+ #expect(Array(out.history.keys) == [old.url])+ #expect(out.ranking.queriesToSelected == ["old": old.url])+ #expect(out.ranking.recentlySwitchedToTabs == [tab: [now.addingTimeInterval(-7200)]])+ #expect(out.ranking.commandUsage == ["settings": 2])+ }++ /// All time also forgets picks of pages that are open tabs (not in history at all).+ @Test func allTimeClearsEverything() {+ let e = HistoryEntry(url: "https://a.example/", title: "A", lastVisit: now, visitCount: 9)+ let ranking = RankingData(recentlySwitchedToTabs: [UUID(): [now]], queriesToSelected: ["a": e.url, "yt": "https://www.youtube.com/"])+ let out = BrowsingDataClear.clearing(.allTime, history: [e.url: e], ranking: ranking)+ #expect(out.history.isEmpty)+ #expect(out.ranking.queriesToSelected.isEmpty)+ #expect(out.ranking.recentlySwitchedToTabs.isEmpty)+ }++ @Test func olderThan30DaysKeepsRecentPages() {+ let old = HistoryEntry(url: "https://old.example/", title: "Old", lastVisit: now.addingTimeInterval(-40 * 86400), visitCount: 1)+ let new = HistoryEntry(url: "https://new.example/", title: "New", lastVisit: now, visitCount: 1)+ let out = BrowsingDataClear.clearing(.before(now.addingTimeInterval(-30 * 86400)), history: [old.url: old, new.url: new], ranking: RankingData())+ #expect(Array(out.history.keys) == [new.url])+ }+}diff --git a/Packages/CraCore/Tests/CraCoreTests/CommandBarDedupeTests.swift b/Packages/CraCore/Tests/CraCoreTests/CommandBarDedupeTests.swiftnew file mode 100644index 0000000..008de8d--- /dev/null+++ b/Packages/CraCore/Tests/CraCoreTests/CommandBarDedupeTests.swift@@ -0,0 +1,78 @@+import CraCore+import Testing++/// The command bar lists a page once, and an open tab keeps its row.+struct CommandBarDedupeTests {+ typealias Row = CommandBarDedupe.Row++ @Test func comparableAddress() {+ #expect(CommandBarDedupe.comparableURL("https://www.semrush.com/projects/") == "https://semrush.com/projects")+ #expect(CommandBarDedupe.comparableURL("https://semrush.com/projects") == "https://semrush.com/projects")+ #expect(CommandBarDedupe.comparableURL("https://YouTube.com") == "https://youtube.com")+ #expect(CommandBarDedupe.comparableURL("https://www.youtube.com/") == "https://youtube.com")+ #expect(CommandBarDedupe.comparableURL("https://www.youtube.com/watch?v=x") == "https://youtube.com/watch?v=x")+ }++ /// Arc 1.171: "semrush" completes to semrush.com/projects, "umami" to umami.kildahl.dk/dashboard.+ @Test func completionAddress() {+ #expect(CommandBarDedupe.completionAddress("https://www.semrush.com/projects/") == "semrush.com/projects")+ #expect(CommandBarDedupe.completionAddress("https://umami.kildahl.dk/dashboard") == "umami.kildahl.dk/dashboard")+ #expect(CommandBarDedupe.completionAddress("https://youtube.com") == "youtube.com")+ }++ /// YouTube pages share titles, so they also match by host and title.+ @Test func keys() {+ #expect(CommandBarDedupe.keys(id: "hist:x", url: "https://www.youtube.com/?app=desktop", title: "YouTube")+ == ["https://youtube.com?app=desktop", "www.youtube.com|youtube"])+ #expect(CommandBarDedupe.keys(id: "hist:y", url: "https://example.com/a/", title: "A") == ["https://example.com/a"])+ #expect(CommandBarDedupe.keys(id: "cmd:settings", url: nil, title: "Settings") == ["cmd:settings"])+ }++ /// X, 1 Nov 2026: "YouTube" history (many visits) outscored the pinned YouTube tab and took+ /// its row; Return then opened a new tab. The tab keeps the row, at the history's score.+ @Test func openTabWinsItsPage() {+ let tab = CommandBarDedupe.keys(id: "tab:1", url: "https://youtube.com", title: "YouTube")+ let history = CommandBarDedupe.keys(id: "hist:1", url: "https://www.youtube.com/", title: "YouTube")+ let rows = [Row(keys: history, score: 128, isOpenTab: false),+ Row(keys: ["https://youtube.com/feed"], score: 72, isOpenTab: false),+ Row(keys: tab, score: 100, isOpenTab: true)]+ let kept = CommandBarDedupe.kept(rows)+ #expect(kept.map(\.index) == [2, 1])+ #expect(kept.map(\.score) == [128, 72])+ }++ /// Arc 1.171 hid both address variants of the pinned Semrush tab's page and kept another page.+ @Test func addressVariantsFoldIntoTheTab() {+ func row(_ url: String, _ title: String, _ score: Double, tab: Bool = false) -> Row {+ Row(keys: CommandBarDedupe.keys(id: url, url: url, title: title), score: score, isOpenTab: tab)+ }+ let rows = [row("https://semrush.com/projects/", "Semrush nowww variant", 110),+ row("https://www.semrush.com/projects", "Semrush noslash variant", 105),+ row("https://www.semrush.com/analytics/", "Semrush analytics control", 90),+ row("https://www.semrush.com/projects/", "Semrush", 100, tab: true)]+ #expect(CommandBarDedupe.kept(rows).map(\.index) == [3, 2])+ }++ /// Without an open tab the best row stays; of two open tabs, the better one.+ @Test func bestRowOtherwise() {+ let history = [Row(keys: ["a"], score: 60, isOpenTab: false), Row(keys: ["a"], score: 80, isOpenTab: false)]+ #expect(CommandBarDedupe.kept(history).map(\.index) == [1])+ let tabs = [Row(keys: ["a"], score: 90, isOpenTab: true), Row(keys: ["a"], score: 95, isOpenTab: true), Row(keys: ["a"], score: 99, isOpenTab: false)]+ #expect(CommandBarDedupe.kept(tabs).map(\.index) == [1])+ #expect(CommandBarDedupe.kept(tabs).map(\.score) == [99])+ }++ /// A row sharing one key with each of two others joins them into one page.+ @Test func sharedKeysChain() {+ let rows = [Row(keys: ["p1", "t"], score: 50, isOpenTab: false), Row(keys: ["p2"], score: 60, isOpenTab: true),+ Row(keys: ["p2", "t"], score: 40, isOpenTab: false)]+ #expect(CommandBarDedupe.kept(rows).map(\.index) == [1])+ }++ /// Different pages all stay, best first; equal scores keep their order.+ @Test func distinctRowsStayInScoreOrder() {+ let rows = [Row(keys: ["a"], score: 50, isOpenTab: false), Row(keys: ["b"], score: 70, isOpenTab: true), Row(keys: ["c"], score: 50, isOpenTab: false)]+ #expect(CommandBarDedupe.kept(rows).map(\.index) == [1, 0, 2])+ #expect(CommandBarDedupe.kept([]).isEmpty)+ }+}diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swiftindex 393e2fc..cafb1e6 100644--- a/Sources/Cra/Services/BrowserManager.swift+++ b/Sources/Cra/Services/BrowserManager.swift@@ -465,6 +465,40 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {return id}+ // MARK: Delete browsing data++ /// Chrome's Settings page (its Delete browsing data dialog) runs in Chromium; the command+ /// bar's history is Cra's. Hear the dialog's "Delete data" and clear the same history here.+ /// One wait per page (a second load finds the first); the page answers once, then it waits+ /// again.+ private func watchClearBrowsingData(_ browser: CraBrowser) {+ let js = """+ (() => {+ if (typeof chrome === 'undefined' || typeof chrome.send !== 'function') return null;+ return window.__craClearBrowsingData ??= new Promise(resolve => {+ const send = chrome.send;+ chrome.send = function (name, args) {+ if (name === 'clearBrowsingData') {+ chrome.send = send;+ window.__craClearBrowsingData = null;+ resolve(JSON.stringify((args ?? []).slice(1)));+ }+ return send.apply(this, arguments);+ };+ });+ })()+ """+ let params: [String: Any] = ["expression": js, "returnByValue": true, "awaitPromise": true]+ let json = String(data: try! JSONSerialization.data(withJSONObject: params), encoding: .utf8)!+ browser.sendDevToolsMethod("Runtime.evaluate", params: json) { [weak self, weak browser] result, _ in+ DispatchQueue.main.async {+ guard let self, let browser, let message = Self.stringResult(result) else { return }+ if let range = BrowsingDataClear.historyRange(messageJSON: message, now: self.clock.now) { self.store.clearHistory(range) }+ if browser.currentURL.hasPrefix("chrome://settings") { self.watchClearBrowsingData(browser) }+ }+ }+ }+// MARK: Picture in Picture/// Arc: "Enable Picture in Picture when you leave a video tab". The request@@ -479,6 +513,27 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {requestPictureInPicture(tabID, automatic: true)}+ /// The window is out of sight: covered by another app, on another desktop or in the Dock.+ private(set) var windowCovered = false++ /// Arc's presentPipForOccludedWindow: a window out of sight and not key leaves its video tabs+ /// the way a tab switch does (a four-finger swipe to another desktop, another app on top), and+ /// the video comes back when the window is key again. Only pages playing sound are asked:+ /// the automatic request wants an unmuted video playing, and a page without one in its main+ /// frame gets the activation nudge, which an app switch shouldn't send to every page.+ func windowVisibilityChanged(covered: Bool) {+ guard covered != windowCovered else { return }+ windowCovered = covered+ for id in visibleTabIDs {+ guard let rt = runtimes[id] else { continue }+ if covered {+ if rt.browser.isAudible { leaveTab(id) }+ } else if rt.autoPictureInPicture || rt.pendingAutoPictureInPicture {+ returnToTab(rt)+ }+ }+ }+func browser(_ browser: CraBrowser, didChangePictureInPicturePlayback playing: Bool) {PictureInPictureChrome.shared.isPlaying = playing}@@ -522,7 +577,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {rt.autoPictureInPicture = rt.pendingAutoPictureInPicturert.pendingAutoPictureInPicture = false// The request from leaving the tab landed after the user came back.- if rt.autoPictureInPicture, id == visibleTabID { browser.exitPictureInPicture() }+ if rt.autoPictureInPicture, id == visibleTabID, !windowCovered { browser.exitPictureInPicture() }} else {rt.autoPictureInPicture = false}@@ -687,6 +742,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {guard let id = tabID(of: browser) else { return }log(id, "loaded \(site(url, id, browser)) (HTTP \(statusCode))")guard !browser.isIncognito else { return }+ if url.hasPrefix("chrome://settings") { watchClearBrowsingData(browser) }store.recordVisit(url: url, title: title.isEmpty ? (store.item(id)?.tab?.savedTitle ?? "") : title)}diff --git a/Sources/Cra/Services/SidebarStore.swift b/Sources/Cra/Services/SidebarStore.swiftindex b3c7411..b22725d 100644--- a/Sources/Cra/Services/SidebarStore.swift+++ b/Sources/Cra/Services/SidebarStore.swift@@ -1567,6 +1567,14 @@ final class SidebarStore {rankingFile.save(ranking)}+ /// Chrome's Delete browsing data deleted history: the command bar forgets it too.+ func clearHistory(_ range: BrowsingDataClear.Range) {+ (history, ranking) = BrowsingDataClear.clearing(range, history: history, ranking: ranking)+ historyFile.saveNow(Array(history.values))+ rankingFile.saveNow(ranking)+ CraLog.note("history cleared (\(range == .allTime ? "all time" : "a time range"))")+ }+func recordCommandUse(_ id: String) {ranking.commandUsage[id, default: 0] += 1rankingFile.save(ranking)diff --git a/Sources/Cra/Services/SuggestionEngine.swift b/Sources/Cra/Services/SuggestionEngine.swiftindex 70c89c4..971276e 100644--- a/Sources/Cra/Services/SuggestionEngine.swift+++ b/Sources/Cra/Services/SuggestionEngine.swift@@ -441,35 +441,38 @@ final class SuggestionEngine {return 0}- /// Arc dedups by title+host for sites whose tabs share titles- /// (command_bar_behavior.json: dedupByTitleAndHostList).- private static let dedupHosts: Set<String> = ["figma.com", "www.figma.com", "notion.so", "www.notion.so", "github.com",- "zoom.us", "maps.google.com", "console.cloud.google.com", "app.slack.com",- "linear.app", "www.youtube.com", "docs.google.com", "mail.google.com"]-private func dedupe(_ items: [Suggestion]) -> [Suggestion] {- var seen: Set<String> = []- var out: [Suggestion] = []- for s in items.sorted(by: { $0.score > $1.score }) {- var key = s.id- if let url = s.url, let host = URL(string: url)?.host?.lowercased() {- key = Self.dedupHosts.contains(host) ? "\(host)|\(s.title.lowercased())" : url- if case .command = s.kind { key = s.id }- }- if seen.insert(key).inserted { out.append(s) }+ let rows = items.map { s -> CommandBarDedupe.Row in+ let isCommand: Bool+ if case .command = s.kind { isCommand = true } else { isCommand = false }+ return CommandBarDedupe.Row(keys: CommandBarDedupe.keys(id: s.id, url: isCommand ? nil : s.url, title: s.title),+ score: s.score, isOpenTab: s.tabID != nil)+ }+ return CommandBarDedupe.kept(rows).map { kept in+ var s = items[kept.index]+ s.score = kept.score+ return s}- return out}private func inlineCompletion(_ q: String, candidates: [Suggestion]) -> (text: String, candidateID: String)? {guard !q.contains(" "), q.count >= 2, !Self.looksLikeURL(q) || !q.contains("/") else { return nil }- for c in candidates {- guard let url = c.url, c.score >= 90 || c.kind == .topDomain, let host = URL(string: url)?.host?.lowercased() else { continue }+ func completion(_ c: Suggestion) -> String? {+ guard let url = c.url, c.score >= 90 || c.kind == .topDomain, let host = URL(string: url)?.host?.lowercased() else { return nil }let bare = host.hasPrefix("www.") ? String(host.dropFirst(4)) : host- if bare.hasPrefix(q) && bare != q { return (bare, c.id) }- if host.hasPrefix(q) && host != q { return (host, c.id) }+ if bare.hasPrefix(q) && bare != q { return bare }+ if host.hasPrefix(q) && host != q { return host }+ return nil}- return nil+ guard let best = candidates.lazy.compactMap({ c in completion(c).map { (text: $0, candidateID: c.id) } }).first else { return nil }+ // An open tab on the completed host leads, so Return switches to it rather than opening the+ // site again from history, and completes to its whole address (Arc 1.171: "semrush" →+ // semrush.com/projects for a tab on www.semrush.com/projects/).+ if let tab = candidates.first(where: { $0.tabID != nil && completion($0) == best.text }), let url = tab.url {+ let address = CommandBarDedupe.completionAddress(url)+ return (address.lowercased().hasPrefix(q) && address.count > q.count ? address : best.text, tab.id)+ }+ return best}// MARK: Formattingdiff --git a/Sources/Cra/UI/CommandBar/CommandTextField.swift b/Sources/Cra/UI/CommandBar/CommandTextField.swiftindex 1c80086..466973a 100644--- a/Sources/Cra/UI/CommandBar/CommandTextField.swift+++ b/Sources/Cra/UI/CommandBar/CommandTextField.swift@@ -107,9 +107,14 @@ final class CommandTextField {suppressChange = false}- /// If a completion suffix is selected, Enter means "go there".+ /// If a completion suffix is selected, Enter means "go there". A completion an open tab+ /// supplies leads the list as its "Switch to Tab" row, and Enter switches to that tab, as+ /// in Arc 1.171 ("youtube" → youtube.com with a pinned YouTube). Asking again for the+ /// completed address put the typed row first and opened the site in a new tab instead+ /// (reported on X, 1 Nov 2026).private func acceptSelectedCompletion(_ textView: NSTextView) {guard pendingCompletion != nil, textView.selectedRange.length > 0 else { return }+ if controller.result.inlineCompletion == pendingCompletion, controller.result.items.first?.tabID != nil { return }lastTyped = textView.stringcontroller.update(query: textView.string, allowCompletion: false)}diff --git a/Sources/Cra/UI/Settings/PrivacyPane.swift b/Sources/Cra/UI/Settings/PrivacyPane.swiftindex dc4aab6..9242f00 100644--- a/Sources/Cra/UI/Settings/PrivacyPane.swift+++ b/Sources/Cra/UI/Settings/PrivacyPane.swift@@ -3,9 +3,12 @@ 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; "Connections"-/// is Chrome's "Always use secure connections".+/// is Chrome's "Always use secure connections". "Data" holds Arc's Clear Browsing Data (Arc keeps+/// it in Settings ▸ Profiles and opens Chrome's Privacy and security page; Cra opens Chrome's+/// Delete browsing data dialog itself, the step after).struct PrivacyPane: View {@Environment(SidebarStore.self) private var store+ let actions: SettingsActionsvar body: some View {@Bindable var store = store@@ -37,6 +40,19 @@ struct PrivacyPane: View {}}SettingsFootnote("Pages load over HTTPS. Before opening a site that doesn’t support it, Cra warns you first.")++ SettingsHeader("Data").padding(.top, 20)+ SettingsCard {+ SettingsCardRow {+ HStack(spacing: 5.5) {+ SettingsGlyph(symbol: "trash.fill", color: Color(nsColor: .systemGray))+ Text("Browsing data").font(.system(size: 13))+ }+ } trailing: {+ Button("Clear Browsing Data…") { actions.openURL(BrowsingDataClear.pageURL) }+ }+ }+ SettingsFootnote("Delete history, cookies and cached files for the current space’s profile. History you delete also leaves the command bar.")}}}diff --git a/Sources/Cra/UI/Settings/SettingsWindowController.swift b/Sources/Cra/UI/Settings/SettingsWindowController.swiftindex de16d80..b0aac3d 100644--- a/Sources/Cra/UI/Settings/SettingsWindowController.swift+++ b/Sources/Cra/UI/Settings/SettingsWindowController.swift@@ -221,7 +221,7 @@ struct SettingsContent: View {switch nav.pane {case .general: GeneralPane()case .tabs: TabsPane()- case .privacy: PrivacyPane()+ case .privacy: PrivacyPane(actions: actions)case .profiles: ProfilesPane()case .extensions: ExtensionsPane(actions: actions)case .shortcuts: ShortcutsPane()diff --git a/Sources/Cra/UI/TabSwitcher/TabSwitcher.swift b/Sources/Cra/UI/TabSwitcher/TabSwitcher.swiftindex e129459..9d53935 100644--- a/Sources/Cra/UI/TabSwitcher/TabSwitcher.swift+++ b/Sources/Cra/UI/TabSwitcher/TabSwitcher.swift@@ -47,9 +47,10 @@ final class TabSwitcher {func cycle(_ delta: Int, event: NSEvent?, items make: () -> [Item]) {if isOpen { move(delta); return }let list = make()- guard list.count > 1 else { return }+ // Arc 1.171 shows the switcher with one open tab too (its only card); with none, nothing.+ guard !list.isEmpty else { return }items = list- selectedIndex = delta > 0 ? 1 : list.count - 1+ selectedIndex = list.count == 1 ? 0 : delta > 0 ? 1 : list.count - 1isOpen = true// From a menu or the command bar nothing is held: switch straight away.let pressed = event.flatMap { $0.type == .keyDown ? $0.modifierFlags : nil } ?? []@@ -71,9 +72,9 @@ final class TabSwitcher {/// Testing: open on the second card without a held key.func debugOpen(_ list: [Item]) {- guard list.count > 1 else { return }+ guard !list.isEmpty else { return }items = list- selectedIndex = 1+ selectedIndex = min(1, list.count - 1)isOpen = trueonShow()}diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swiftindex 61b5d31..1663da5 100644--- a/Sources/Cra/UI/Windows/MainWindowController.swift+++ b/Sources/Cra/UI/Windows/MainWindowController.swift@@ -1315,8 +1315,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM// 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 { !panes.contains($0) && (!store.isPinned($0) || app.runtime(for: $0) != nil) }+ let back = openRecentTabs(limit: .max).first { !panes.contains($0) }store.selectTab(back, window: windowID)}} else {@@ -1324,6 +1323,14 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM}}+ /// The space's open tabs, the latest first. A pinned tab that was closed (unloaded) isn't+ /// open: ⌃Tab doesn't list it and ⌘W doesn't go back to it.+ private func openRecentTabs(limit: Int) -> [UUID] {+ Array(store.recentTabs(in: focusedSpaceID, limit: .max)+ .filter { $0 == selectedTabID || !store.isPinned($0) || app.runtime(for: $0) != nil }+ .prefix(limit))+ }+func resetPinnedTab(_ id: UUID) {guard let home = store.resetPinnedTab(id) else { return }app.runtime(for: id)?.browser.loadURL(home)@@ -1929,7 +1936,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMtabSwitcher.isDark = darktabSwitcher.highlight = theme.switcherHighlight(dark: dark)tabSwitcher.palette = theme.palette- tabSwitcher.debugOpen(store.recentTabs(in: focusedSpaceID, limit: TabSwitcherMetrics.maxItems).compactMap { id in+ tabSwitcher.debugOpen(openRecentTabs(limit: TabSwitcherMetrics.maxItems).compactMap { id inguard let it = store.item(id), let tab = it.tab else { return nil }return TabSwitcher.Item(id: id, title: it.displayTitle, iconKey: tab.iconKey, snapshot: browsers.runtime(for: id)?.snapshot)})@@ -2068,7 +2075,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMtabSwitcher.palette = theme.palette}tabSwitcher.cycle(delta, event: event) {- store.recentTabs(in: focusedSpaceID, limit: TabSwitcherMetrics.maxItems).compactMap { id in+ openRecentTabs(limit: TabSwitcherMetrics.maxItems).compactMap { id inguard let it = store.item(id), let tab = it.tab else { return nil }return TabSwitcher.Item(id: id, title: it.displayTitle, iconKey: tab.iconKey, snapshot: browsers.runtime(for: id)?.snapshot)}@@ -2380,6 +2387,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMfunc windowDidBecomeKey(_ notification: Notification) {guard (notification.object as? NSWindow) === window else { return }shell.windowActive = true+ browsers.windowVisibilityChanged(covered: false)reclaimPages()}@@ -2407,6 +2415,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM}func windowDidResignKey(_ notification: Notification) {+ if (notification.object as? NSWindow) === window { leaveIfCovered() }guard (notification.object as? NSWindow) === commandPanel, commandBar.isOpen else { return }if Date().timeIntervalSince(commandBarOpenedAt) < 0.6 {DispatchQueue.main.async { [weak self] in@@ -2433,6 +2442,26 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMshell.needsLayout = true}+ func windowDidChangeOcclusionState(_ notification: Notification) {+ guard (notification.object as? NSWindow) === window else { return }+ leaveIfCovered()+ }++ /// Arc's autoPictureInPictureOnWindowOccluded: a window that isn't key and is completely out+ /// of sight (another app or desktop in front, minimised) sends its video to Picture in+ /// Picture, checked when it resigns key and when what covers it changes; the video comes home+ /// when the window is key again (windowDidBecomeKey). Arc 1.171, 2 Nov 2026: hiding an Arc that+ /// had not been active opened nothing; losing focus with its window on another desktop did.+ /// A locked screen covers every window and leaves nothing.+ private func leaveIfCovered() {+ guard let window, !window.isKeyWindow, !window.occlusionState.contains(.visible), !Self.screenIsLocked else { return }+ browsers.windowVisibilityChanged(covered: true)+ }++ private static var screenIsLocked: Bool {+ (CGSessionCopyCurrentDictionary() as? [String: Any])?["CGSSessionScreenIsLocked"] as? Bool ?? false+ }+/// The frame lives in the store's observed prefs, which every sidebar row reads (selection):/// it is stored once a resize or move settles, not on every step of it.private func saveFrame() {diff --git a/Tests/BrowserManagerLifecycleTests.swift b/Tests/BrowserManagerLifecycleTests.swiftindex d43075f..da14066 100644--- a/Tests/BrowserManagerLifecycleTests.swift+++ b/Tests/BrowserManagerLifecycleTests.swift@@ -86,6 +86,7 @@ enum BrowserManagerLifecycleTests {nowPlayingCase()await nowPlayingPictureInPictureCase()await leaveVideoTabPictureInPictureCase()+ await coveredWindowPictureInPictureCase()pageColoursCase()await sleepCase("malformed or missing replies cannot authorize sleeping", reply: nil) { _, _ in }await pageProbeCase()@@ -385,6 +386,45 @@ enum BrowserManagerLifecycleTests {manager.closeAll()}+ /// A window out of sight and not key (another app or desktop in front) leaves its video tab+ /// like a tab switch, as Arc's presentPipForOccludedWindow does, and the video comes back when+ /// the window is key again (X report, 1 Nov 2026). Silent pages aren't asked, and a Picture in+ /// Picture the user opened stays.+ @MainActor+ private static func coveredWindowPictureInPictureCase() async {+ let store = SidebarStore()+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView())+ let a = store.createTab(url: "https://example.test/video").id+ let ra = manager.ensureRuntime(for: a)!+ store.settings.autoPictureInPicture = true+ manager.show(a, focus: false)++ manager.windowVisibilityChanged(covered: true)+ expect(!ra.browser.replies.contains { $0.method == "Runtime.evaluate" }, "a covered window doesn't ask a silent page")+ manager.windowVisibilityChanged(covered: false)++ ra.browser.isAudible = true+ manager.windowVisibilityChanged(covered: true)+ expect(ra.browser.lastParams.contains(#""userGesture":true"#) && ra.browser.lastParams.contains("})(true)"),+ "a covered window asks its playing page for automatic Picture in Picture")+ ra.browser.reply(to: "Runtime.evaluate", with: #"{"result":{"type":"string","value":"ok"}}"#)+ await drainMainQueue()+ ra.browser.isInPictureInPicture = true+ manager.browser(ra.browser, didChangePictureInPicture: true)+ expect(ra.browser.isInPictureInPicture, "the tab is still the one in front, but out of sight: the video stays out")+ manager.windowVisibilityChanged(covered: false)+ expect(!ra.browser.isInPictureInPicture, "the window back in sight brings the video home")+ manager.browser(ra.browser, didChangePictureInPicture: false)++ ra.browser.isInPictureInPicture = true+ manager.browser(ra.browser, didChangePictureInPicture: true)+ manager.windowVisibilityChanged(covered: true)+ expect(!ra.browser.replies.contains { $0.method == "Runtime.evaluate" }, "a page already in Picture in Picture isn't asked again")+ manager.windowVisibilityChanged(covered: false)+ expect(ra.browser.isInPictureInPicture, "Picture in Picture the user opened stays when the window shows again")+ manager.closeAll()+ }+/// A woken page's toolbar starts in the colour its page last reported (Arc, #46), and a tab/// coming on screen asks its page for its background again unless the page is still loading.@MainActordiff --git a/Tests/BrowserManagerSupport/AppServices.swift b/Tests/BrowserManagerSupport/AppServices.swiftindex bd68052..f84afa0 100644--- a/Tests/BrowserManagerSupport/AppServices.swift+++ b/Tests/BrowserManagerSupport/AppServices.swift@@ -28,6 +28,7 @@ enum TestRoot { case today }}func setThemeColor(_ id: UUID, _ hex: String) { items[id]?.tab?.themeColor = hex }func recordVisit(url: String, title: String) {}+ func clearHistory(_ range: BrowsingDataClear.Range) {}func selectTab(_ id: UUID, window: UUID?) {}func markUnread(_ id: UUID, _ unread: Bool) {}@discardableResult@@ -39,6 +40,10 @@ enum TestRoot { case today }}}enum FaviconKey { static func key(for url: String) -> String? { url } }+enum BrowsingDataClear {+ enum Range { case allTime }+ static func historyRange(messageJSON: String, now: Date) -> Range? { nil }+}final class FaviconCache {func store(_ image: NSImage, forKey: String, persist: Bool) {}}