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.
Arc import keeps each space's profile: sign-ins, pins and extensions follow it (#131) (#141)
Victor Kildahlac48c03f823e
diff --git a/Packages/CraCore/Sources/CraCore/ExtensionProfiles.swift b/Packages/CraCore/Sources/CraCore/ExtensionProfiles.swiftnew file mode 100644index 0000000..2564c60--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/ExtensionProfiles.swift@@ -0,0 +1,83 @@+import Foundation++/// extension-profiles.json: the Chromium profile folders ("Default", "Profile <id>") each folder in+/// Extensions/ loads in, by folder name. Chromium loads those folders with --load-extension, which+/// installs them in every profile; Cra's CEF build skips a profile the list leaves out+/// (--cra-load-extension-profiles), so such an extension is not installed there at all. A folder+/// with no list loads in every profile, as every one did before GitHub #131. The import fills it+/// from the browser profiles that had the extension, as Arc keeps extensions per profile.+public struct ExtensionProfiles: Codable, Equatable, Sendable {+ public var folders: [String: [String]]++ public init(folders: [String: [String]] = [:]) {+ self.folders = folders+ }++ /// The profile folders `folder` loads in; nil for every profile.+ public func profiles(ofFolder folder: String) -> Set<String>? { folders[folder].map(Set.init) }++ public func loads(folder: String, inProfile profile: String) -> Bool { profiles(ofFolder: folder)?.contains(profile) ?? true }++ /// An extension imported into `folder` for `profiles` (nil: every profile). A folder that was+ /// already there without a list keeps loading everywhere; one with a list gets the new profiles too.+ public mutating func add(folder: String, profiles: Set<String>?, folderExisted: Bool) {+ if folderExisted && folders[folder] == nil { return }+ guard let profiles else { folders[folder] = nil; return }+ folders[folder] = profiles.union(folders[folder] ?? []).sorted()+ }++ public mutating func remove(folder: String) { folders[folder] = nil }++ /// --cra-load-extension-profiles for the --load-extension `folders` in that order: each one's+ /// profiles joined by "|", "*" for every profile. nil when every folder loads everywhere.+ public func commandLineValue(forFolders names: [String]) -> String? {+ let values = names.map { name in folders[name].map { $0.sorted().joined(separator: "|") } ?? "*" }+ return values.allSatisfy { $0 == "*" } ? nil : values.joined(separator: ",")+ }++ public init(from decoder: Decoder) throws {+ folders = try decoder.singleValueContainer().decode([String: [String]].self)+ }++ public func encode(to encoder: Encoder) throws {+ var c = encoder.singleValueContainer()+ try c.encode(folders)+ }+}++/// Where an import from a browser with profiles lands in Cra's profiles (GitHub #131). Arc binds+/// each space to a Chromium profile in its `User Data` folder; the import gives each of those but+/// Default a Cra profile, and what came from a source profile (sign-ins, pins, extensions) goes+/// to that Cra profile. Source profiles no imported space uses go to Default, where everything+/// went before.+public struct ImportProfileMap: Equatable, Sendable {+ /// Cra's profile folder by source profile folder, for the source profiles of imported spaces.+ public var folders: [String: String]++ public init(folders: [String: String] = [:]) {+ self.folders = folders+ }++ public func craFolder(forSource source: String?) -> String { source.flatMap { folders[$0] } ?? "Default" }++ /// True when the import put a space on a profile of its own.+ public var bindsProfiles: Bool { folders.values.contains { $0 != "Default" } }++ /// The Cra profiles an extension the source had in `sources` loads in: nil (every profile)+ /// when the import bound no profiles, or when that is every profile Cra has (`allFolders`).+ public func extensionProfiles(sources: Set<String>, allFolders: Set<String>) -> Set<String>? {+ guard bindsProfiles else { return nil }+ let targets = Set(sources.map { craFolder(forSource: $0) })+ return targets.isEmpty || allFolders.isSubset(of: targets) ? nil : targets+ }++ /// Arc's `profile` of a space: `{"custom": {"_0": {"directoryBasename": "Profile 2", …}}}`, or+ /// `{"default": true}` for the Default profile (nil). Only a "Profile <n>" folder name counts:+ /// it is read as a path under Arc's User Data.+ public static func arcProfileFolder(_ profile: Any?) -> String? {+ guard let custom = (profile as? [String: Any])?["custom"] as? [String: Any],+ let folder = (custom["_0"] as? [String: Any])?["directoryBasename"] as? String,+ folder.hasPrefix("Profile "), !folder.contains("/"), !folder.contains("..") else { return nil }+ return folder+ }+}diff --git a/Packages/CraCore/Sources/CraCore/PinnedExtensions.swift b/Packages/CraCore/Sources/CraCore/PinnedExtensions.swiftindex 73834fb..d12939d 100644--- a/Packages/CraCore/Sources/CraCore/PinnedExtensions.swift+++ b/Packages/CraCore/Sources/CraCore/PinnedExtensions.swift@@ -39,6 +39,13 @@ public struct PinnedExtensions: Codable, Equatable, Sendable {profiles[profile] = list}+ /// A new profile's pins from the browser it was imported from (GitHub #131); a profile that+ /// already has a list of its own keeps it.+ public mutating func seed(_ ids: [String], inProfile profile: String) {+ guard profiles[profile] == nil, ids != shared else { return }+ profiles[profile] = ids+ }+/// Drops the extensions `isGone` says are no longer installed, from every list.public mutating func removeAll(where isGone: (String) -> Bool) {shared.removeAll(where: isGone)diff --git a/Packages/CraCore/Tests/CraCoreTests/ExtensionProfilesTests.swift b/Packages/CraCore/Tests/CraCoreTests/ExtensionProfilesTests.swiftnew file mode 100644index 0000000..2ffb86b--- /dev/null+++ b/Packages/CraCore/Tests/CraCoreTests/ExtensionProfilesTests.swift@@ -0,0 +1,73 @@+import CraCore+import Foundation+import Testing++/// Extensions and sign-ins follow the Arc profile a space was on (GitHub #131).+struct ExtensionProfilesTests {+ @Test func aFolderWithoutAListLoadsEverywhere() {+ let p = ExtensionProfiles(folders: ["a": ["Profile 1"]])+ #expect(p.loads(folder: "b", inProfile: "Default") && p.profiles(ofFolder: "b") == nil)+ #expect(p.loads(folder: "a", inProfile: "Profile 1") && !p.loads(folder: "a", inProfile: "Default"))+ }++ @Test func importAddsProfiles() {+ var p = ExtensionProfiles()+ p.add(folder: "a", profiles: ["Profile 1"], folderExisted: false)+ p.add(folder: "a", profiles: ["Default"], folderExisted: true)+ #expect(p.folders["a"] == ["Default", "Profile 1"], "a second import adds its profiles")+ p.add(folder: "b", profiles: ["Profile 1"], folderExisted: true)+ #expect(p.profiles(ofFolder: "b") == nil, "an extension already loading everywhere keeps doing so")+ p.add(folder: "a", profiles: nil, folderExisted: true)+ #expect(p.profiles(ofFolder: "a") == nil, "imported for every profile: the list goes")+ p.add(folder: "c", profiles: ["Profile 2"], folderExisted: false)+ p.remove(folder: "c")+ #expect(p.folders.isEmpty)+ }++ @Test func commandLineFollowsTheLoadExtensionOrder() {+ let p = ExtensionProfiles(folders: ["b": ["Profile 2", "Default"]])+ #expect(p.commandLineValue(forFolders: ["a", "b", "c"]) == "*,Default|Profile 2,*")+ #expect(p.commandLineValue(forFolders: ["a", "c"]) == nil, "no switch when every folder loads everywhere")+ #expect(ExtensionProfiles(folders: ["a": []]).commandLineValue(forFolders: ["a"]) == "", "an empty list loads nowhere")+ }++ @Test func savedAsAPlainObject() throws {+ let p = ExtensionProfiles(folders: ["a": ["Default"]])+ #expect(String(decoding: try JSONEncoder().encode(p), as: UTF8.self) == #"{"a":["Default"]}"#)+ #expect(try JSONDecoder().decode(ExtensionProfiles.self, from: Data("{}".utf8)) == ExtensionProfiles())+ }++ @Test func arcSpaceProfiles() throws {+ func parse(_ json: String) throws -> String? {+ ImportProfileMap.arcProfileFolder(try JSONSerialization.jsonObject(with: Data(json.utf8)))+ }+ #expect(try parse(#"{"custom": {"_0": {"directoryBasename": "Profile 2", "machineID": "m"}}}"#) == "Profile 2")+ #expect(try parse(#"{"default": true}"#) == nil)+ #expect(try parse(#"{"custom": {"_0": {"directoryBasename": "Default"}}}"#) == nil)+ #expect(ImportProfileMap.arcProfileFolder(nil) == nil)+ #expect(try parse(#"{"custom": {"_0": {"directoryBasename": "Profile 2/../../x"}}}"#) == nil, "never a path out of User Data")+ }++ @Test func importedExtensionsGoWhereTheirProfilesWent() {+ let map = ImportProfileMap(folders: ["Profile 2": "Profile A", "Profile 7": "Profile B"])+ let all: Set<String> = ["Default", "Profile A", "Profile B"]+ #expect(map.craFolder(forSource: "Profile 2") == "Profile A")+ #expect(map.craFolder(forSource: "Profile 5") == "Default", "a profile no imported space uses goes to Default")+ #expect(map.craFolder(forSource: nil) == "Default")+ #expect(map.extensionProfiles(sources: ["Profile 2"], allFolders: all) == ["Profile A"])+ #expect(map.extensionProfiles(sources: ["Profile 2", "Profile 5"], allFolders: all) == ["Profile A", "Default"])+ #expect(map.extensionProfiles(sources: ["Default", "Profile 2", "Profile 7"], allFolders: all) == nil,+ "in every profile: loads everywhere, as before")+ #expect(ImportProfileMap(folders: ["Default": "Default"]).extensionProfiles(sources: ["Profile 3"], allFolders: all) == nil,+ "an import that bound no profiles changes nothing")+ }++ @Test func importedPinsSeedOnlyNewLists() {+ var pins = PinnedExtensions(shared: ["a"])+ pins.seed(["b", "c"], inProfile: "Profile A")+ pins.seed(["a"], inProfile: "Profile B")+ pins.seed(["z"], inProfile: "Profile A")+ #expect(pins.ids(inProfile: "Profile A") == ["b", "c"])+ #expect(pins.profiles["Profile B"] == nil, "the same list as everyone's stays shared")+ }+}diff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/input/extension-profiles.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/input/extension-profiles.jsonnew file mode 100644index 0000000..c11f05d--- /dev/null+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/input/extension-profiles.json@@ -0,0 +1 @@+{"aeblfdkhhhdcdjpifhhbdiojplfjncoa":["Profile B0000000-0000-0000-0000-000000000001"],"pfjdepjjfjjahkjfpkcgfmfhmnakjfba":["Default","Profile B0000000-0000-0000-0000-000000000002"]}\ No newline at end of filediff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/extension-profiles.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/extension-profiles.jsonnew file mode 100644index 0000000..c11f05d--- /dev/null+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/extension-profiles.json@@ -0,0 +1 @@+{"aeblfdkhhhdcdjpifhhbdiojplfjncoa":["Profile B0000000-0000-0000-0000-000000000001"],"pfjdepjjfjjahkjfpkcgfmfhmnakjfba":["Default","Profile B0000000-0000-0000-0000-000000000002"]}\ No newline at end of filediff --git a/Packages/CraCore/Tests/CraCoreTests/ModelFixtureTests.swift b/Packages/CraCore/Tests/CraCoreTests/ModelFixtureTests.swiftindex 671502e..be5a26b 100644--- a/Packages/CraCore/Tests/CraCoreTests/ModelFixtureTests.swift+++ b/Packages/CraCore/Tests/CraCoreTests/ModelFixtureTests.swift@@ -104,6 +104,15 @@ struct ModelFixtureTests {}}+ /// extension-profiles.json (#131): a folder's profiles; a folder it doesn't name loads everywhere.+ @Test func extensionProfilesLoadAsRecorded() throws {+ let (loaded, recorded) = try Self.load("extension-profiles.json", as: ExtensionProfiles.self)+ #expect(loaded == recorded)+ #expect(try Self.roundTrips(loaded))+ #expect(!loaded.loads(folder: "aeblfdkhhhdcdjpifhhbdiojplfjncoa", inProfile: "Default"))+ #expect(loaded.loads(folder: "some-folder", inProfile: "Profile 9"))+ }+// MARK: What the old shapes turn into@Test func legacySidebarGetsWhatTheStoreRepairsFrom() throws {diff --git a/Sources/Cra/App/main.swift b/Sources/Cra/App/main.swiftindex 7e86190..cf0dcb9 100644--- a/Sources/Cra/App/main.swift+++ b/Sources/Cra/App/main.swift@@ -30,13 +30,17 @@ MainActor.assumeIsolated {SafeStorage.prepare(profileIsFree: profileIsFree)if profileIsFree {let profile = AppPaths.chromiumCache.appendingPathComponent("Default", isDirectory: true)- if CredentialImport.hasPending { CredentialImport.applyPending(profileDir: profile) }+ if CredentialImport.hasPending { CredentialImport.applyPending(root: AppPaths.chromiumCache) }CredentialImport.repairImportedCookies(profileDir: profile)ProfileCleanup.run()}NativeMessagingHosts.link(into: AppPaths.chromiumCache)+ let extensions = ExtensionStore.loadList()+ CraCEFRuntime.setExtensionPaths(extensions.paths, profiles: extensions.profiles)+ if let p = extensions.profiles { CraLog.note("extension profiles: \(p)") }+let useChromeStyle = ProcessInfo.processInfo.environment["CRA_CHROME_STYLE"] == "1"let started = CraCEFRuntime.initialize(withCachePath: AppPaths.chromiumCache.path,userAgentProduct: "",diff --git a/Sources/Cra/Services/ExtensionStore.swift b/Sources/Cra/Services/ExtensionStore.swiftindex a80afbb..02a3c2d 100644--- a/Sources/Cra/Services/ExtensionStore.swift+++ b/Sources/Cra/Services/ExtensionStore.swift@@ -27,8 +27,8 @@ final class ExtensionStore {/// Installed by Chrome into the profile (Web Store); Chrome owns the folder and/// loads changes at once, so removing goes through chrome://extensions.var managedByChrome = false- /// Chromium profile folders ("Default", "Profile <id>") it is installed in; nil for the- /// --load-extension ones, which Chromium loads into every profile.+ /// Chromium profile folders ("Default", "Profile <id>") it is installed in; nil for an+ /// --load-extension one that loads into every profile (extension-profiles.json, GitHub #131).var profiles: Set<String>?/// Profile folders where it is turned off in chrome://extensions. Chromium keeps it off/// there across launches, also when --load-extension loads the folder again.@@ -51,13 +51,31 @@ final class ExtensionStore {/// CraCEF loads the same folder (it also honours CRA_DATA_DIR).nonisolated static var directory: URL { AppPaths.supportDir.appendingPathComponent("Extensions", isDirectory: true) }+ /// The folders --load-extension loads at start-up, in name order, and the switch that says+ /// which profiles load each (CraCEFRuntime.setExtensionPaths).+ nonisolated static func loadList() -> (paths: [String], profiles: String?) {+ let fm = FileManager.default+ let names = ((try? fm.contentsOfDirectory(atPath: directory.path)) ?? []).sorted()+ .filter { fm.fileExists(atPath: directory.appendingPathComponent($0).appendingPathComponent("manifest.json").path) }+ return (names.map { directory.appendingPathComponent($0, isDirectory: true).path }, loadProfiles().commandLineValue(forFolders: names))+ }+nonisolated static func isInstalled(id: String) -> Bool {FileManager.default.fileExists(atPath: directory.appendingPathComponent(id).appendingPathComponent("manifest.json").path)}/// Copies an extension imported from Arc or Dia in as Extensions/<id>,- /// replacing an older copy of the same extension.- nonisolated static func importExtension(_ ext: ImportableExtension) throws {+ /// replacing an older copy of the same extension. It loads in `profiles` (nil: every+ /// profile) from the next launch.+ nonisolated static func importExtension(_ ext: ImportableExtension, profiles: Set<String>?) throws {+ let existed = isInstalled(id: ext.id)+ try importExtension(ext)+ var scopes = loadProfiles()+ scopes.add(folder: ext.id, profiles: profiles, folderExisted: existed)+ try saveProfiles(scopes)+ }++ private nonisolated static func importExtension(_ ext: ImportableExtension) throws {let fm = FileManager.defaulttry fm.createDirectory(at: directory, withIntermediateDirectories: true)let dest = directory.appendingPathComponent(ext.id, isDirectory: true)@@ -70,6 +88,23 @@ final class ExtensionStore {try fm.moveItem(at: staging, to: dest)}+ // MARK: Profiles of the Extensions/ folders (GitHub #131)++ nonisolated private static var profilesFile: URL { AppPaths.file("extension-profiles.json") }++ nonisolated static func loadProfiles() -> ExtensionProfiles {+ guard let data = try? Data(contentsOf: profilesFile) else { return ExtensionProfiles() }+ return (try? JSONDecoder().decode(ExtensionProfiles.self, from: data)) ?? ExtensionProfiles()+ }++ nonisolated private static func saveProfiles(_ profiles: ExtensionProfiles) throws {+ if profiles.folders.isEmpty {+ try? FileManager.default.removeItem(at: profilesFile)+ } else {+ try JSONEncoder().encode(profiles).write(to: profilesFile, options: .atomic)+ }+ }+private(set) var entries: [Entry] = []/// Set once the folder changed in this session; a restart loads the change.private(set) var needsRestart = false@@ -88,9 +123,11 @@ final class ExtensionStore {let profiles = ((try? fm.contentsOfDirectory(atPath: root.path)) ?? []).filter { $0 == "Default" || $0.hasPrefix("Profile ") }.sorted()let settings = Dictionary(uniqueKeysWithValues: profiles.map { ($0, Self.extensionSettings(inProfile: $0)) })let disabled = settings.mapValues(ExtensionImporter.disabledIDs(settings:))+ let scopes = Self.loadProfiles()let list = names.sorted().compactMap { name -> Entry? inguard var entry = Self.entry(id: name, folder: ExtensionStore.directory.appendingPathComponent(name, isDirectory: true),extensionID: nil) else { return nil }+ entry.profiles = scopes.profiles(ofFolder: name)entry.disabledProfiles = Set(profiles.filter { disabled[$0]?.contains(entry.extensionID) == true })return entry}@@ -225,10 +262,8 @@ final class ExtensionStore {private static func loadPinned() -> PinnedExtensions {if let data = try? Data(contentsOf: pinnedFile) { return (try? JSONDecoder().decode(PinnedExtensions.self, from: data)) ?? PinnedExtensions() }for source in [ImportSource.arc, .dia] + ImportSource.allCases.filter({ $0.id == "chrome" }) {- let prefs = source.dataDir.appendingPathComponent("Default/Preferences")- guard let data = try? Data(contentsOf: prefs),- let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],- let ids = (json["extensions"] as? [String: Any])?["pinned_extensions"] as? [String], !ids.isEmpty else { continue }+ guard let ids = ExtensionImporter.pinnedIDs(inProfile: source.dataDir.appendingPathComponent("Default", isDirectory: true)),+ !ids.isEmpty else { continue }return PinnedExtensions(shared: ids)}return PinnedExtensions()@@ -245,6 +280,20 @@ final class ExtensionStore {if pinned != before { savePinned() }}+ /// The pins a profile had in the browser the import came from (GitHub #131): a profile the+ /// import made gets them as its own. Default's become everyone's list while Cra has none+ /// saved yet, as they would at the first launch after the import (loadPinned).+ func seedPinned(_ ids: [String], inProfile profile: String) {+ let before = pinned+ if profile == "Default" {+ guard !FileManager.default.fileExists(atPath: Self.pinnedFile.path), pinned.shared.isEmpty else { return }+ pinned.shared = ids+ } else {+ pinned.seed(ids, inProfile: profile)+ }+ if pinned != before { savePinned() }+ }+func movePinned(_ id: String, to index: Int, inProfile profile: String) {let before = pinnedpinned.move(id, to: index, inProfile: profile)@@ -527,6 +576,11 @@ final class ExtensionStore {func remove(_ entry: Entry) {try? FileManager.default.removeItem(at: entry.url)+ if !entry.managedByChrome {+ var scopes = Self.loadProfiles()+ scopes.remove(folder: entry.id)+ try? Self.saveProfiles(scopes)+ }needsRestart = truereload()}diff --git a/Sources/Cra/Services/Import/BrowserSources.swift b/Sources/Cra/Services/Import/BrowserSources.swiftindex d8765dc..7cb2f84 100644--- a/Sources/Cra/Services/Import/BrowserSources.swift+++ b/Sources/Cra/Services/Import/BrowserSources.swift@@ -36,10 +36,10 @@ struct ImportSource: Identifiable, Hashable {}static let arc = ImportSource(id: "arc", name: "Arc", bundleID: "company.thebrowser.Browser", kind: .arc,- dataDir: support.appendingPathComponent("Arc/User Data", isDirectory: true),+ dataDir: ArcImporter.userData,keychainService: "Arc Safe Storage", keychainAccount: "Arc")static let dia = ImportSource(id: "dia", name: "Dia", bundleID: "company.thebrowser.dia", kind: .dia,- dataDir: support.appendingPathComponent("Dia/User Data", isDirectory: true),+ dataDir: DiaImporter.userData,keychainService: "Dia Safe Storage", keychainAccount: "Dia")static let allCases: [ImportSource] = [diff --git a/Sources/Cra/Services/Import/ChromiumImporter.swift b/Sources/Cra/Services/Import/ChromiumImporter.swiftindex 6478bf5..724cd86 100644--- a/Sources/Cra/Services/Import/ChromiumImporter.swift+++ b/Sources/Cra/Services/Import/ChromiumImporter.swift@@ -16,12 +16,7 @@ enum ChromiumImporter {/// Opera keeps its single profile in the root itself.static func profiles(userData: URL) -> [ChromiumProfile] {let fm = FileManager.default- var names: [String: String] = [:]- if let data = try? Data(contentsOf: userData.appendingPathComponent("Local State")),- let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],- let cache = (root["profile"] as? [String: Any])?["info_cache"] as? [String: Any] {- for (dir, info) in cache { if let n = (info as? [String: Any])?["name"] as? String { names[dir] = n } }- }+ let names = profileNames(userData: userData)let dirs = ((try? fm.contentsOfDirectory(atPath: userData.path)) ?? []).filter { $0 == "Default" || $0.hasPrefix("Profile ") }.sorted { $0 == "Default" ? true : ($1 == "Default" ? false : $0.localizedStandardCompare($1) == .orderedAscending) }@@ -34,6 +29,14 @@ enum ChromiumImporter {return out}+ /// Local State's profile.info_cache: the name the browser shows for each profile folder.+ static func profileNames(userData: URL) -> [String: String] {+ guard let data = try? Data(contentsOf: userData.appendingPathComponent("Local State")),+ let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let cache = (root["profile"] as? [String: Any])?["info_cache"] as? [String: Any] else { return [:] }+ return cache.compactMapValues { ($0 as? [String: Any])?["name"] as? String }+ }+private static func hasData(_ dir: URL) -> Bool {["Bookmarks", "History", "Cookies", "Login Data"].contains { FileManager.default.fileExists(atPath: dir.appendingPathComponent($0).path) }}@@ -223,11 +226,11 @@ enum ChromiumImporter {if cookies, let db = SQLiteSnapshot(copying: p.dir.appendingPathComponent("Cookies"))?? SQLiteSnapshot(copying: p.dir.appendingPathComponent("Network/Cookies")) {readAny = true- out.cookies += readCookies(db, key: key)+ out.cookies += readCookies(db, key: key).map { var c = $0; c.sourceProfile = p.id; return c }}if passwords, let db = SQLiteSnapshot(copying: p.dir.appendingPathComponent("Login Data")) {readAny = true- out.logins += readLogins(db, key: key)+ out.logins += readLogins(db, key: key).map { var l = $0; l.sourceProfile = p.id; return l }}}if !readAny && (cookies || passwords) { throw CredentialImportError.unreadable(browser) }diff --git a/Sources/Cra/Services/Import/CredentialImport.swift b/Sources/Cra/Services/Import/CredentialImport.swiftindex 9cc07f3..4f13265 100644--- a/Sources/Cra/Services/Import/CredentialImport.swift+++ b/Sources/Cra/Services/Import/CredentialImport.swift@@ -8,7 +8,8 @@ import SQLite3// and ImportPasswordsAndCookiesResultView). Sources decrypt with their own key;// rows are re-encrypted for Cra's Chromium profile and staged in a file, then// written into Cookies / Login Data on the next launch before Chromium opens-// them (Chromium keeps both databases locked while it runs).+// them (Chromium keeps both databases locked while it runs). Rows from an Arc+// profile go to the Cra profile its spaces were put on (GitHub #131).struct ImportedCookie: Codable {var host: String // host_key: ".example.com" for domain cookies@@ -23,6 +24,8 @@ struct ImportedCookie: Codable {var httpOnly: Bool/// Chromium CookieSameSite: -1 unspecified, 0 none, 1 lax, 2 strict.var sameSite: Int+ /// The source browser's profile folder it was read from.+ var sourceProfile: String?}struct ImportedLogin: Codable {@@ -34,6 +37,8 @@ struct ImportedLogin: Codable {var password: Stringvar signonRealm: Stringvar created: Int64+ /// The source browser's profile folder it was read from.+ var sourceProfile: String?/// A login from a CSV or Firefox: the realm is the page's origin.init?(url: String, username: String, password: String, created: Int64 = ChromiumTime.now) {@@ -229,8 +234,9 @@ enum CredentialImport {/// Staged rows, already encrypted for Cra's profile (SafeStorage.key), so the/// file is no easier to read than the databases it feeds.private struct Pending: Codable {- struct Cookie: Codable { var c: ImportedCookie; var encrypted: Data }- struct Login: Codable { var l: ImportedLogin; var encrypted: Data }+ /// `profile`: the Cra profile folder it goes to; nil (files from before #131) is Default.+ struct Cookie: Codable { var c: ImportedCookie; var encrypted: Data; var profile: String? }+ struct Login: Codable { var l: ImportedLogin; var encrypted: Data; var profile: String? }var cookies: [Cookie] = []var logins: [Login] = []}@@ -238,21 +244,22 @@ enum CredentialImport {static var pendingFile: URL { AppPaths.file("pending-credentials.json") }static var hasPending: Bool { FileManager.default.fileExists(atPath: pendingFile.path) }- /// Adds to whatever is already staged; returns false when nothing could be written.+ /// Adds to whatever is already staged, each row for the Cra profile `profiles` maps its+ /// source profile to; returns false when nothing could be written.@discardableResult- static func stage(_ creds: ImportedCredentials) -> Bool {+ static func stage(_ creds: ImportedCredentials, profiles: ImportProfileMap = ImportProfileMap()) -> Bool {guard !creds.isEmpty else { return true }guard let key = SafeStorage.key else { return false }var pending = (try? Data(contentsOf: pendingFile)).flatMap { try? JSONDecoder().decode(Pending.self, from: $0) } ?? Pending()for var c in creds.cookies {let encrypted = ChromiumCrypto.encrypt(Data(c.value.utf8), key: key)c.value = ""- pending.cookies.append(.init(c: c, encrypted: encrypted))+ pending.cookies.append(.init(c: c, encrypted: encrypted, profile: profiles.craFolder(forSource: c.sourceProfile)))}for var l in creds.logins {let encrypted = ChromiumCrypto.encrypt(Data(l.password.utf8), key: key)l.password = ""- pending.logins.append(.init(l: l, encrypted: encrypted))+ pending.logins.append(.init(l: l, encrypted: encrypted, profile: profiles.craFolder(forSource: l.sourceProfile)))}return write(pending)}@@ -286,21 +293,69 @@ enum CredentialImport {return write(pending)}- /// Called from main.swift before Chromium starts. Leaves the file in place- /// when the profile's databases are missing (no first run yet) or busy.- static func applyPending(profileDir: URL) {+ /// Called from main.swift before Chromium starts, with the folder that holds the profiles.+ /// A profile Chromium has not made yet gets its databases from Default's schema, so its spaces+ /// are signed in from their first page. Rows stay in the file while their profile's databases+ /// are missing (no first run yet) or busy.+ static func applyPending(root: URL) {guard let data = try? Data(contentsOf: pendingFile),- let pending = try? JSONDecoder().decode(Pending.self, from: data),+ var pending = try? JSONDecoder().decode(Pending.self, from: data),let key = SafeStorage.key else { return }- let cookiesOK = pending.cookies.isEmpty || insertCookies(pending.cookies, into: profileDir.appendingPathComponent("Cookies"), key: key)- let loginsOK = pending.logins.isEmpty || insertLogins(pending.logins, into: profileDir.appendingPathComponent("Login Data"))- if cookiesOK && loginsOK {+ let template = root.appendingPathComponent("Default", isDirectory: true)+ let folders = Set(pending.cookies.map { $0.profile ?? "Default" } + pending.logins.map { $0.profile ?? "Default" })+ for folder in folders.sorted() {+ let dir = root.appendingPathComponent(folder, isDirectory: true)+ let cookies = pending.cookies.filter { ($0.profile ?? "Default") == folder }+ let logins = pending.logins.filter { ($0.profile ?? "Default") == folder }+ let cookiesDB = dir.appendingPathComponent("Cookies"), loginsDB = dir.appendingPathComponent("Login Data")+ if folder != "Default" {+ if !cookies.isEmpty { createDatabase(cookiesDB, like: template.appendingPathComponent("Cookies")) }+ if !logins.isEmpty { createDatabase(loginsDB, like: template.appendingPathComponent("Login Data")) }+ }+ let cookiesOK = cookies.isEmpty || insertCookies(cookies, into: cookiesDB, key: key)+ let loginsOK = logins.isEmpty || insertLogins(logins, into: loginsDB)+ if cookiesOK { pending.cookies.removeAll { ($0.profile ?? "Default") == folder } }+ if loginsOK { pending.logins.removeAll { ($0.profile ?? "Default") == folder } }+ if !cookiesOK || !loginsOK { NSLog("Cra: imported passwords/cookies for \(folder) stay pending (cookies \(cookiesOK), logins \(loginsOK))") }+ }+ if pending.cookies.isEmpty && pending.logins.isEmpty {try? FileManager.default.removeItem(at: pendingFile)} else {- NSLog("Cra: imported passwords/cookies stay pending (cookies \(cookiesOK), logins \(loginsOK))")+ _ = write(pending)}}+ /// An empty database with `template`'s tables, indexes and meta rows (Chromium's schema+ /// version), for a profile Chromium has not opened yet. Nothing when `url` exists.+ static func createDatabase(_ url: URL, like template: URL) {+ let fm = FileManager.default+ guard !fm.fileExists(atPath: url.path), fm.fileExists(atPath: template.path) else { return }+ var source: OpaquePointer?+ guard sqlite3_open_v2(template.path, &source, SQLITE_OPEN_READONLY, nil) == SQLITE_OK else { sqlite3_close(source); return }+ let schema = SQLite.rows(source, "SELECT sql FROM sqlite_master WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%' ORDER BY type = 'table' DESC, rowid")+ .compactMap { $0["sql"] as? String }+ let meta = SQLite.rows(source, "SELECT key, value FROM meta")+ sqlite3_close(source)+ guard !schema.isEmpty, !meta.isEmpty else { return }+ // Owner only, as Chromium makes its profile folders and databases.+ try? fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])+ let staging = url.deletingLastPathComponent().appendingPathComponent(".\(url.lastPathComponent).creating")+ try? fm.removeItem(at: staging)+ var db: OpaquePointer?+ guard sqlite3_open_v2(staging.path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nil) == SQLITE_OK else { sqlite3_close(db); return }+ let ok = transaction(db) {+ for sql in schema where sqlite3_exec(db, sql, nil, nil, nil) != SQLITE_OK { return false }+ for row in meta {+ guard let k = row["key"] as? String else { return false }+ if !insert(db, table: "meta", values: ["key": k, "value": row["value"] ?? ""], orIgnore: false) { return false }+ }+ return true+ }+ sqlite3_close(db)+ guard ok, (try? fm.setAttributes([.posixPermissions: 0o600], ofItemAtPath: staging.path)) != nil else { try? fm.removeItem(at: staging); return }+ try? fm.moveItem(at: staging, to: url)+ }+private static func open(_ url: URL) -> OpaquePointer? {guard FileManager.default.fileExists(atPath: url.path) else { return nil }var db: OpaquePointer?diff --git a/Sources/Cra/Services/Import/ExtensionImporter.swift b/Sources/Cra/Services/Import/ExtensionImporter.swiftindex dbe454c..a80be1c 100644--- a/Sources/Cra/Services/Import/ExtensionImporter.swift+++ b/Sources/Cra/Services/Import/ExtensionImporter.swift@@ -9,8 +9,17 @@ struct ImportableExtension: Identifiable {let name: Stringlet version: Stringlet folder: URL- let isEnabled: Bool+ /// Turned on in at least one of `profiles`.+ var isEnabled: Boollet icon: NSImage?+ /// The source profile folders it is installed in, and whether it is on there (GitHub #131).+ var profiles: [String: Bool] = [:]++ /// Where Cra loads it: the profiles that have it on, else (picked though off) every one that has it.+ var sourceProfiles: Set<String> {+ let on = Set(profiles.filter(\.value).keys)+ return on.isEmpty ? Set(profiles.keys) : on+ }}enum ExtensionImporter {@@ -22,19 +31,35 @@ enum ExtensionImporter {extensions(inUserData: supportDir.appendingPathComponent("User Data", isDirectory: true))}- /// Every profile under a Chromium "User Data" folder (Chrome, Brave, Edge… keep it at the top level).+ /// Every profile under a Chromium "User Data" folder (Chrome, Brave, Edge… keep it at the top level),+ /// one entry per extension with the profiles that have it.static func extensions(inUserData userData: URL) -> [ImportableExtension] {let profiles = ((try? FileManager.default.contentsOfDirectory(atPath: userData.path)) ?? []).filter { $0 == "Default" || $0.hasPrefix("Profile ") }.sorted()- var seen = Set<String>()var out: [ImportableExtension] = []for profile in profiles {let dir = userData.appendingPathComponent(profile, isDirectory: true)- for e in extensions(inProfile: dir) where seen.insert(e.id).inserted { out.append(e) }+ for e in extensions(inProfile: dir) {+ if let i = out.firstIndex(where: { $0.id == e.id }) {+ out[i].profiles[profile] = e.isEnabled+ out[i].isEnabled = out[i].isEnabled || e.isEnabled+ } else {+ var e = e+ e.profiles = [profile: e.isEnabled]+ out.append(e)+ }+ }}return out.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }}+ /// The profile's pinned extensions (Chromium's extensions.pinned_extensions), in toolbar order.+ static func pinnedIDs(inProfile dir: URL) -> [String]? {+ guard let data = try? Data(contentsOf: dir.appendingPathComponent("Preferences")),+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }+ return (json["extensions"] as? [String: Any])?["pinned_extensions"] as? [String]+ }+/// extensions.settings by extension ID, from the profile's files. Newer Chromium keeps/// extension state in Secure Preferences; older in Preferences.static func settings(inProfile dir: URL) -> [String: Any] {diff --git a/Sources/Cra/Services/Import/Importers.swift b/Sources/Cra/Services/Import/Importers.swiftindex ddda8ec..2136f30 100644--- a/Sources/Cra/Services/Import/Importers.swift+++ b/Sources/Cra/Services/Import/Importers.swift@@ -24,6 +24,14 @@ struct ImportedSpace {var favorites: [ImportedItem] = []var pinned: [ImportedItem] = []var today: [ImportedItem] = []+ /// The source browser's profile the space was on, when it is not Default (Arc, GitHub #131).+ var profile: ImportedProfile?+}++/// A Chromium profile of the source browser: its folder under `User Data` and the name it shows.+struct ImportedProfile: Hashable {+ var folder: String+ var name: String}struct ImportedArchiveEntry {@@ -116,6 +124,9 @@ enum ArcImporter {static var isAvailable: Bool { FileManager.default.fileExists(atPath: supportDir.appendingPathComponent("StorableSidebar.json").path) }+ /// Arc's Chromium profiles: Default and "Profile <n>", one per profile a space can be on.+ static var userData: URL { supportDir.appendingPathComponent("User Data", isDirectory: true) }+/// Arc's View ▸ Show Toolbar (topBarURLEnabled, off by default); nil when Arc never stored it.static var showsToolbar: Bool? {UserDefaults(suiteName: "company.thebrowser.Browser")?.object(forKey: "topBarURLEnabled") as? Bool@@ -159,6 +170,9 @@ enum ArcImporter {return nil}+ // Each space is on a Chromium profile in User Data, named as Arc's space menu shows it.+ let profileNames = ChromiumImporter.profileNames(userData: userData)+// Favorites (topApps): one container per profile, shared by that profile's spaces.var favoritesByProfile: [(profile: NSDictionary, items: [ImportedItem])] = []var allFavorites: [ImportedItem] = []@@ -193,6 +207,7 @@ enum ArcImporter {var sp = ImportedSpace(title: title, emoji: emoji, theme: ArcThemeImport.theme(from: space) ?? SpaceTheme.presets[0])let profile = space["profile"] as? NSDictionarysp.favorites = favoritesByProfile.first { $0.profile.isEqual(profile) }?.items ?? allFavorites+ sp.profile = ImportProfileMap.arcProfileFolder(space["profile"]).map { ImportedProfile(folder: $0, name: profileNames[$0] ?? $0) }if let p = pinnedID, let c = items[p] { sp.pinned = (c["childrenIds"] as? [String] ?? []).compactMap(convert) }if let t = todayID, let c = items[t] { sp.today = (c["childrenIds"] as? [String] ?? []).compactMap(convert) }plan.spaces.append(sp)@@ -389,7 +404,11 @@ enum DiaImporter {// MARK: - Applyingextension SidebarStore {- struct ImportResult { var spaces = 0; var tabs = 0; var folders = 0; var archived = 0; var spaceIDs: [UUID] = [] }+ struct ImportResult {+ var spaces = 0; var tabs = 0; var folders = 0; var archived = 0; var spaceIDs: [UUID] = []+ /// The Cra profile each source profile of an imported space landed in.+ var profiles = ImportProfileMap()+ }/// Add a plan to the sidebar. Like Dia, every imported space is a new one (importing/// twice gives two of each), so people pick what to keep; a taken title gets a number@@ -463,8 +482,21 @@ extension SidebarStore {return "\(title) \(n)"}+ // A source profile becomes a Cra profile of the same name (one already there is reused, so+ // importing again doesn't add "Work" twice); its spaces go on it, the rest stay on Default.+ func craProfile(for source: ImportedProfile) -> BrowserProfile {+ profiles.first { $0.name == source.name } ?? createProfile(name: source.name)+ }+for sp in plan.spaces {let space = createSpace(title: freeTitle(sp.title), emoji: sp.emoji, theme: sp.theme, focus: false)+ if let source = sp.profile {+ let folder = result.profiles.folders[source.folder] ?? craProfile(for: source).directoryName+ result.profiles.folders[source.folder] = folder+ if let p = profiles.first(where: { $0.directoryName == folder }) { setProfile(p.id, forSpace: space.id) }+ } else {+ result.profiles.folders["Default"] = "Default"+ }result.spaces += 1result.spaceIDs.append(space.id)if imported[sp.title.lowercased()] == nil { imported[sp.title.lowercased()] = space.id }diff --git a/Sources/Cra/UI/Onboarding/ImportFlow.swift b/Sources/Cra/UI/Onboarding/ImportFlow.swiftindex 08bef1a..27cd43e 100644--- a/Sources/Cra/UI/Onboarding/ImportFlow.swift+++ b/Sources/Cra/UI/Onboarding/ImportFlow.swift@@ -90,6 +90,8 @@ final class ImportFlowModel {private(set) var finished = falseprivate(set) var importedExtensionCount = 0private var importedSpaceID: UUID?+ /// The Cra profiles the import put the source's profiles on (Arc, GitHub #131).+ private var importedProfiles = ImportProfileMap()// Default browser step: Dia's NewDefaultBrowserViewModel options.var setAsDefault = true@@ -279,6 +281,21 @@ final class ImportFlowModel {func continueFromSpaces() { if extensions.isEmpty { startImport(withExtensions: false) } else { go(.extensions) } }+ /// The profiles an extension will load in, by name, while the picked spaces bring Arc profiles+ /// along; nil when it loads in every profile (GitHub #131).+ func profileNames(of e: ImportableExtension) -> [String]? {+ guard let plan else { return nil }+ var map = ImportProfileMap()+ var names = ["Default": "Default"]+ for sp in plan.selecting(spaces: selectedSpaces, favorites: false).spaces {+ if let p = sp.profile { map.folders[p.folder] = p.folder; names[p.folder] = p.name } else { map.folders["Default"] = "Default" }+ }+ // Cra profiles the import doesn't reuse keep counting as profiles the extension may miss.+ let others = store.profiles.filter { p in !names.values.contains(p.name) }.map(\.directoryName)+ guard let targets = map.extensionProfiles(sources: e.sourceProfiles, allFolders: Set(["Default"] + map.folders.values + others)) else { return nil }+ return targets.sorted { $0 == "Default" || ($1 != "Default" && (names[$0] ?? $0) < (names[$1] ?? $1)) }.map { names[$0] ?? $0 }+ }+// MARK: Passwords and cookiesfunc toggleProfile(_ id: String) {@@ -467,8 +484,9 @@ final class ImportFlowModel {let result = store.apply(selection, includeArchive: includeArchive, includeSettings: includeSettings,replacing: emptyBefore.map(\.id))importedSpaceID = result.spaceIDs.first+ importedProfiles = result.profilesfavicons.reset()- let creds = credentials+ let creds = credentials, profiles = result.profilesTask { @MainActor in// Dia paces the tiles (ImportProgressController.progressUIIntervals) so// each category visibly lands; the sidebar work above is already done.@@ -480,7 +498,7 @@ final class ImportFlowModel {case "passwords", "cookies":// Both land in one staged file; the first tile writes it.if !credentialsStaged && credentialError == nil {- let ok = await Task.detached(priority: .userInitiated) { CredentialImport.stage(creds) }.value+ let ok = await Task.detached(priority: .userInitiated) { CredentialImport.stage(creds, profiles: profiles) }.valuecredentialsStaged = okif !ok { credentialError = "Cra could not save the imported passwords and cookies." }}@@ -493,15 +511,34 @@ final class ImportFlowModel {categories[i].state = .done}}+ // After the extensions are in: a reload drops pins of extensions Cra doesn't have.+ seedPinnedExtensions(profiles)finished = true}}+ /// Each profile the import used shows the toolbar pins its source profile had; Default first,+ /// so its list is in place before the file exists.+ private func seedPinnedExtensions(_ map: ImportProfileMap) {+ guard let source, map.bindsProfiles else { return }+ for (folder, target) in map.folders.sorted(by: { $0.value == "Default" && $1.value != "Default" }) {+ guard let ids = ExtensionImporter.pinnedIDs(inProfile: source.dataDir.appendingPathComponent(folder, isDirectory: true)) else { continue }+ ExtensionStore.shared.seedPinned(ids, inProfile: target)+ }+ }++ /// The Cra profiles an extension loads in: those the import put its source profiles on.+ private func targetProfiles(of ext: ImportableExtension) -> Set<String>? {+ importedProfiles.extensionProfiles(sources: ext.sourceProfiles, allFolders: Set(["Default"] + store.profiles.map(\.directoryName)))+ }+private func importExtensions(_ chosen: [ImportableExtension], tile i: Int) async {var failed: [String] = []for ext in chosen {+ let profiles = targetProfiles(of: ext)+ if let profiles { CraLog.note("import: extension \(ext.id) for \(profiles.sorted().joined(separator: ", "))") }let ok = await Task.detached(priority: .userInitiated) { () -> Bool in- (try? ExtensionStore.importExtension(ext)) != nil+ (try? ExtensionStore.importExtension(ext, profiles: profiles)) != nil}.valueif ok { importedExtensionCount += 1 } else { failed.append(ext.name) }}diff --git a/Sources/Cra/UI/Onboarding/ImportFlowViews.swift b/Sources/Cra/UI/Onboarding/ImportFlowViews.swiftindex 55a43c0..1c0da33 100644--- a/Sources/Cra/UI/Onboarding/ImportFlowViews.swift+++ b/Sources/Cra/UI/Onboarding/ImportFlowViews.swift@@ -287,10 +287,13 @@ private struct ExtensionsStep: View {VStack(alignment: .leading, spacing: 8) {ForEach(model.extensions) { e inlet installed = ExtensionStore.isInstalled(id: e.id)+ // Arc keeps extensions per profile: say which profiles it goes to (#131).+ let profiles = model.profileNames(of: e).map { " · " + $0.joined(separator: ", ") } ?? ""SelectableRow(c: c, checked: model.selectedExtensions.contains(e.id), toggle: { model.toggleExtension(e.id) }) {ExtensionIcon(image: e.icon, size: 24, c: c)RowTitle(title: e.name,- caption: installed ? "Already in Cra · \(e.version)" : (e.isEnabled ? e.version : "Turned off in \(model.source?.rawValue ?? "Arc")"),+ caption: installed ? "Already in Cra · \(e.version)"+ : (e.isEnabled ? e.version + profiles : "Turned off in \(model.source?.rawValue ?? "Arc")"),c: c)}}diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mmindex c181b4b..79df87f 100644--- a/Sources/CraCEF/CraCEF.mm+++ b/Sources/CraCEF/CraCEF.mm@@ -54,7 +54,9 @@ static bool g_quitting = false;static bool g_useChromeStyle = false;static bool g_useMockKeychain = false;/// Resolved by Swift from the chosen profile, including environment-free dev launches.-static NSString* g_extensionsDirectory = nil;+// Extensions/ folders for --load-extension and the profiles each loads in (+setExtensionPaths:profiles:).+static NSArray<NSString*>* g_extensionPaths = nil;+static NSString* g_extensionProfiles = nil;static BOOL g_chromeHosting = NO;static NSMutableArray<CraBrowser*>* g_pendingCreation = nil;@@ -616,15 +618,13 @@ public:command_line->AppendSwitchWithValue("profile-directory", "Default");// Unpacked Chrome extensions (Chrome-style browsers only): one folder per extension.if (process_type.empty()) {- // Use the same resolved data root as AppPaths/ExtensionStore, never an- // independent production fallback when CraDev is opened from Finder.- NSString* dir = g_extensionsDirectory;- NSMutableArray<NSString*>* paths = [NSMutableArray array];- for (NSString* name in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:nil]) {- NSString* p = [dir stringByAppendingPathComponent:name];- if ([[NSFileManager defaultManager] fileExistsAtPath:[p stringByAppendingPathComponent:@"manifest.json"]]) [paths addObject:p];+ // The app lists them from the same data root as AppPaths/ExtensionStore. The+ // command line installs them in every profile; Cra's CEF build skips a profile+ // --cra-load-extension-profiles leaves out (extension-profiles.patch, #131).+ if (g_extensionPaths.count) {+ command_line->AppendSwitchWithValue("load-extension", CefStringFromNS([g_extensionPaths componentsJoinedByString:@","]));+ if (g_extensionProfiles) command_line->AppendSwitchWithValue("cra-load-extension-profiles", CefStringFromNS(g_extensionProfiles));}- if (paths.count) command_line->AppendSwitchWithValue("load-extension", CefStringFromNS([paths componentsJoinedByString:@","]));}command_line->AppendSwitchWithValue("autoplay-policy", "document-user-activation-required");// WebRTC hides this Mac's local IP behind a random .local name announced over@@ -2458,6 +2458,11 @@ static void MarkProfileExitedCleanly(NSString* profileDir) {CefWindow::CreateTopLevelWindow(new SpikeWindowDelegate(view));}++ (void)setExtensionPaths:(NSArray<NSString*>*)paths profiles:(NSString*)profiles {+ g_extensionPaths = [paths copy];+ g_extensionProfiles = [profiles copy];+}++ (BOOL)initializeWithCachePath:(NSString*)cachePathuserAgentProduct:(NSString*)productlogPath:(NSString*)logPath@@ -2466,7 +2471,6 @@ static void MarkProfileExitedCleanly(NSString* profileDir) {if (g_libraryLoader) return YES;g_useChromeStyle = useChromeStyle;g_useMockKeychain = useMockKeychain;- g_extensionsDirectory = [[cachePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Extensions"];g_libraryLoader = new CefScopedLibraryLoader();if (!g_libraryLoader->LoadInMain()) {NSLog(@"CraCEF: failed to load Chromium Embedded Framework");diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.hindex 2093259..0f25a79 100644--- a/Sources/CraCEF/include/CraCEF.h+++ b/Sources/CraCEF/include/CraCEF.h@@ -256,6 +256,10 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {+ (NSInteger)blockedDomainCount;/// The blocking decision for a request made by a page, for diagnostics and tests.+ (BOOL)shouldBlockRequestURL:(NSString *)requestURL onPageURL:(NSString *)pageURL;+/// Unpacked extension folders to load with --load-extension, set before initializing, and+/// for each in the same order the profile folders that load it ("Default|Profile <id>", "*"+/// for every profile), comma-separated; nil when every one loads in every profile.++ (void)setExtensionPaths:(NSArray<NSString *> *)paths profiles:(nullable NSString *)profiles;+ (BOOL)initializeWithCachePath:(NSString *)cachePathuserAgentProduct:(NSString *)productlogPath:(NSString *)logPathdiff --git a/Tests/Fixtures/Arc/README.md b/Tests/Fixtures/Arc/README.mdindex 8c96488..992c96e 100644--- a/Tests/Fixtures/Arc/README.md+++ b/Tests/Fixtures/Arc/README.md@@ -1,4 +1,7 @@A made-up Arc profile in Arc's own file format (Arc 1.170 field names), for the importertests (scripts/test-store.sh) and the onboarding-import scenario (CRA_ARC_DIR). No real-browsing data: every address is on example.com. Two spaces on the default profile, two-favorites, a pinned folder, a split view in Today, two archived tabs and a sidebar width.+browsing data: every address is on example.com. Two spaces, Home on the default profile and+Work on "Profile 2" (named "Client" in User Data/Local State), two favorites, a pinned folder,+a split view in Today, two archived tabs and a sidebar width. Each profile has its own+extensions and pinned extensions in its Preferences: "Fixture Everywhere" in both, "Fixture+Client" only in Profile 2, and "Fixture Personal Off" in Default, turned off.diff --git a/Tests/Fixtures/Arc/StorableSidebar.json b/Tests/Fixtures/Arc/StorableSidebar.jsonindex edc9e67..2fc6122 100644--- a/Tests/Fixtures/Arc/StorableSidebar.json+++ b/Tests/Fixtures/Arc/StorableSidebar.json@@ -31,7 +31,7 @@"id": "work","title": "Work","profile": {- "default": true+ "custom": { "_0": { "directoryBasename": "Profile 2", "machineID": "fixture-machine" } }},"containerIDs": ["pinned",diff --git a/Tests/Fixtures/Arc/User Data/Default/Extensions/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/1.0_0/manifest.json b/Tests/Fixtures/Arc/User Data/Default/Extensions/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/1.0_0/manifest.jsonnew file mode 100644index 0000000..7cab06e--- /dev/null+++ b/Tests/Fixtures/Arc/User Data/Default/Extensions/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/1.0_0/manifest.json@@ -0,0 +1,5 @@+{+ "manifest_version": 3,+ "name": "Fixture Everywhere",+ "version": "1.0"+}diff --git a/Tests/Fixtures/Arc/User Data/Default/Extensions/dddddddddddddddddddddddddddddddd/1.0_0/manifest.json b/Tests/Fixtures/Arc/User Data/Default/Extensions/dddddddddddddddddddddddddddddddd/1.0_0/manifest.jsonnew file mode 100644index 0000000..6030463--- /dev/null+++ b/Tests/Fixtures/Arc/User Data/Default/Extensions/dddddddddddddddddddddddddddddddd/1.0_0/manifest.json@@ -0,0 +1,5 @@+{+ "manifest_version": 3,+ "name": "Fixture Personal Off",+ "version": "1.0"+}diff --git a/Tests/Fixtures/Arc/User Data/Default/Preferences b/Tests/Fixtures/Arc/User Data/Default/Preferencesnew file mode 100644index 0000000..9d4f3ac--- /dev/null+++ b/Tests/Fixtures/Arc/User Data/Default/Preferences@@ -0,0 +1,21 @@+{+ "extensions": {+ "pinned_extensions": [+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+ ],+ "settings": {+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": {+ "location": 1,+ "path": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/1.0_0",+ "state": 1+ },+ "dddddddddddddddddddddddddddddddd": {+ "location": 1,+ "path": "dddddddddddddddddddddddddddddddd/1.0_0",+ "disable_reasons": [+ 1+ ]+ }+ }+ }+}diff --git a/Tests/Fixtures/Arc/User Data/Local State b/Tests/Fixtures/Arc/User Data/Local Statenew file mode 100644index 0000000..f443b5a--- /dev/null+++ b/Tests/Fixtures/Arc/User Data/Local State@@ -0,0 +1,12 @@+{+ "profile": {+ "info_cache": {+ "Default": {+ "name": "Personal"+ },+ "Profile 2": {+ "name": "Client"+ }+ }+ }+}diff --git a/Tests/Fixtures/Arc/User Data/Profile 2/Extensions/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/1.0_0/manifest.json b/Tests/Fixtures/Arc/User Data/Profile 2/Extensions/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/1.0_0/manifest.jsonnew file mode 100644index 0000000..7cab06e--- /dev/null+++ b/Tests/Fixtures/Arc/User Data/Profile 2/Extensions/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/1.0_0/manifest.json@@ -0,0 +1,5 @@+{+ "manifest_version": 3,+ "name": "Fixture Everywhere",+ "version": "1.0"+}diff --git a/Tests/Fixtures/Arc/User Data/Profile 2/Extensions/cccccccccccccccccccccccccccccccc/1.0_0/manifest.json b/Tests/Fixtures/Arc/User Data/Profile 2/Extensions/cccccccccccccccccccccccccccccccc/1.0_0/manifest.jsonnew file mode 100644index 0000000..d29cf5c--- /dev/null+++ b/Tests/Fixtures/Arc/User Data/Profile 2/Extensions/cccccccccccccccccccccccccccccccc/1.0_0/manifest.json@@ -0,0 +1,5 @@+{+ "manifest_version": 3,+ "name": "Fixture Client",+ "version": "1.0"+}diff --git a/Tests/Fixtures/Arc/User Data/Profile 2/Preferences b/Tests/Fixtures/Arc/User Data/Profile 2/Preferencesnew file mode 100644index 0000000..089ee24--- /dev/null+++ b/Tests/Fixtures/Arc/User Data/Profile 2/Preferences@@ -0,0 +1,20 @@+{+ "extensions": {+ "pinned_extensions": [+ "cccccccccccccccccccccccccccccccc",+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+ ],+ "settings": {+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": {+ "location": 1,+ "path": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/1.0_0",+ "state": 1+ },+ "cccccccccccccccccccccccccccccccc": {+ "location": 1,+ "path": "cccccccccccccccccccccccccccccccc/1.0_0",+ "state": 1+ }+ }+ }+}diff --git a/Tests/StoreTests.swift b/Tests/StoreTests.swiftindex 1492fdd..1b0c57d 100644--- a/Tests/StoreTests.swift+++ b/Tests/StoreTests.swift@@ -1,4 +1,5 @@import Foundation+import SQLite3/// The production store and the Arc importer, booted through AppComposition with a manual/// clock and a throwaway data folder: timed work (auto-archive, tab sleep cadence) and the@@ -58,6 +59,68 @@ enum StoreTests {let titles = composition.store.orderedSpaces.map(\.title)expect(titles.contains("Home") && titles.contains("Work"), "the imported spaces are in the sidebar")expect(composition.store.integrityProblems().isEmpty, "the imported sidebar is sound")+ arcProfiles(plan: plan, store: composition.store)+ }++ /// Arc's spaces keep their profiles (GitHub #131): Work is on "Profile 2", named Client.+ @MainActor+ private static func arcProfiles(plan: ImportPlan, store: SidebarStore) {+ expect(plan.spaces[0].profile == nil && plan.spaces[1].profile == ImportedProfile(folder: "Profile 2", name: "Client"),+ "a space on Arc's Default has no profile, one on Profile 2 carries it with Local State's name")+ let work = store.orderedSpaces.first { $0.title == "Work" }!, home = store.orderedSpaces.first { $0.title == "Home" }!+ let client = store.profiles.first { $0.name == "Client" }+ expect(store.profiles.count == 1 && client != nil && work.profileID == client?.id && home.profileID == nil,+ "the import makes one Cra profile per Arc profile besides Default and puts its spaces on it")+ expect(store.profileDirectoryName(space: work.id) == client?.directoryName && store.profileDirectoryName(space: home.id) == "Default",+ "pages of Work load in the new profile's folder")++ let again = store.apply(plan, includeArchive: false, includeSettings: false)+ expect(store.profiles.count == 1 && again.profiles.folders == ["Default": "Default", "Profile 2": client!.directoryName],+ "importing again reuses the profile of the same name")+ let map = again.profiles+ let all: Set<String> = ["Default", client!.directoryName]++ let exts = ExtensionImporter.extensions(inUserData: ArcImporter.userData)+ func ext(_ name: String) -> ImportableExtension { exts.first { $0.name == name }! }+ expect(exts.map(\.name) == ["Fixture Client", "Fixture Everywhere", "Fixture Personal Off"], "one entry per extension across profiles")+ expect(ext("Fixture Everywhere").profiles == ["Default": true, "Profile 2": true] && ext("Fixture Personal Off").profiles == ["Default": false],+ "each extension knows the profiles that have it and whether it is on there")+ expect(map.extensionProfiles(sources: ext("Fixture Everywhere").sourceProfiles, allFolders: all) == nil,+ "an extension in every profile loads everywhere, as before")+ expect(map.extensionProfiles(sources: ext("Fixture Client").sourceProfiles, allFolders: all) == [client!.directoryName],+ "an extension only Client had loads only in its Cra profile")+ expect(map.extensionProfiles(sources: ext("Fixture Personal Off").sourceProfiles, allFolders: all) == ["Default"],+ "a turned-off extension picked anyway goes where it was installed")+ expect(ExtensionImporter.pinnedIDs(inProfile: ArcImporter.userData.appendingPathComponent("Profile 2")) == [String(repeating: "c", count: 32), String(repeating: "a", count: 32)],+ "Arc's pins of a profile come from its Preferences")+ newProfileDatabases()+ }++ /// A profile Chromium hasn't opened gets its sign-in databases with Default's schema (#131).+ private static func newProfileDatabases() {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("cra-db-\(UUID().uuidString)", isDirectory: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let template = root.appendingPathComponent("Default/Cookies"), target = root.appendingPathComponent("Profile X/Cookies")+ try? FileManager.default.createDirectory(at: template.deletingLastPathComponent(), withIntermediateDirectories: true)+ var db: OpaquePointer?+ sqlite3_open(template.path, &db)+ sqlite3_exec(db, """+ CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY, value LONGVARCHAR);+ INSERT INTO meta VALUES ('version', '24'), ('last_compatible_version', '24');+ CREATE TABLE cookies(creation_utc INTEGER NOT NULL, host_key TEXT NOT NULL, name TEXT NOT NULL);+ CREATE UNIQUE INDEX cookies_unique_index ON cookies(host_key, name);+ INSERT INTO cookies VALUES (1, 'example.com', 'secret');+ """, nil, nil, nil)+ sqlite3_close(db)+ CredentialImport.createDatabase(target, like: template)+ sqlite3_open(target.path, &db)+ defer { sqlite3_close(db) }+ let meta = SQLite.rows(db, "SELECT key, value FROM meta ORDER BY key").compactMap { $0["value"] as? String }+ let objects = SQLite.rows(db, "SELECT name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY name").compactMap { $0["name"] as? String }+ expect(meta == ["24", "24"] && objects == ["cookies", "cookies_unique_index", "meta"]+ && SQLite.rows(db, "SELECT 1 FROM cookies").isEmpty, "same tables, index and schema version, none of Default's rows")+ let mode = { (u: URL) in (try? FileManager.default.attributesOfItem(atPath: u.path)[.posixPermissions] as? Int) ?? 0 }+ expect(mode(target) == 0o600 && mode(target.deletingLastPathComponent()) == 0o700, "owner only, like Chromium's own")}/// Dia 1.55's encrypted sidebar (Tests/Fixtures/Dia, rebuilt by its make-fixture.py with thediff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.mdindex 5481c12..aac7e19 100644--- a/docs/arc-reverse-engineering.md+++ b/docs/arc-reverse-engineering.md@@ -2362,6 +2362,28 @@ tap with a real Shift key held around them; the space read from each window's `sreset the URL loader factories. Cra logs the winner and the overridden ones per profile when they change, andExport Diagnostics' summary.txt has a "Proxy:" section.+## Importing Arc's profiles (3 Nov 2026, issue #131, reporter's Arc: seven spaces on six profiles)++- [O static] Each space in StorableSidebar.json names its Chromium profile: `profile` is `{"default": true}` or+ `{"custom": {"_0": {"directoryBasename": "Profile 2", "machineID": …}}}`. The folder's name in Arc's space+ menu is `User Data/Local State` → `profile.info_cache[<folder>].name`. Each profile keeps its own cookies, logins,+ `extensions.settings` and `extensions.pinned_extensions`.+- Cra's import makes one Cra profile per Arc profile besides Default (reusing a Cra profile of the same name) and+ puts the spaces on it. Each Arc profile's cookies and passwords are staged for the Cra profile its spaces landed+ on. A Cra profile Chromium has not opened yet gets Cookies and Login Data with Default's schema and meta rows+ before Chromium starts, so the first page is signed in. Arc's pins become that profile's list. An Arc profile no+ imported space uses goes to Default, as everything did before.+- `--load-extension` installs in every profile (`ExtensionService::Init` runs it per profile, and command-line+ installs are never restored from prefs). `extension-profiles.patch` (CEF codecs9) adds+ `--cra-load-extension-profiles`: for each `--load-extension` path, in order, the profile folders that load it+ ("Default|Profile <id>") or `*`. An imported extension loads only in the Cra profiles of the Arc profiles that+ had it turned on (extension-profiles.json); one every profile had, or one from an import that bound no profiles,+ still loads everywhere. CDP's `Extensions.loadUnpacked`/`uninstall` only reach the default profile, and a+ hand-written `extensions.settings` entry fails Secure Preferences' MAC check, so neither could do this.+- Checked on a test copy with a three-profile fake Arc: each space's page read its own profile's cookie, Chromium's+ per-profile prefs held exactly the probes that profile was given, and the toolbar and Extensions menu differed per+ space as in Arc.+## The tab shown after ⌘W (Arc 1.171, 2 Nov 2026, issue #105, offline Arc driven through its menus)Offline Arc as in "One space": one space with pinned S and P2 and Today C, B, A, D (A, B, C saved with`activeTabBeforeCreationID` and `referrerID` = S, unread), the selected tab and the window'sdiff --git a/scripts/cef-patches/extension-profiles.patch b/scripts/cef-patches/extension-profiles.patchnew file mode 100644index 0000000..0c75625--- /dev/null+++ b/scripts/cef-patches/extension-profiles.patch@@ -0,0 +1,42 @@+diff --git a/chrome/browser/extensions/extension_service.cc b/chrome/browser/extensions/extension_service.cc+--- a/chrome/browser/extensions/extension_service.cc++++ b/chrome/browser/extensions/extension_service.cc+@@ -26,6 +26,7 @@+ #include "base/one_shot_event.h"+ #include "base/stl_util.h"+ #include "base/strings/string_number_conversions.h"++#include "base/strings/string_split.h"+ #include "base/strings/string_tokenizer.h"+ #include "base/strings/stringprintf.h"+ #include "base/strings/utf_string_conversions.h"+@@ -452,7 +453,30 @@ void ExtensionService::LoadExtensionsFromCommandLineFlag(+ base::StringTokenizerT<base::CommandLine::StringType,+ base::CommandLine::StringType::const_iterator>+ t(path_list, FILE_PATH_LITERAL(","));++ // Cra: --cra-load-extension-profiles names, for each --load-extension path in++ // the same order, the profile folders that load it ("Default|Profile <id>"),++ // or "*" for every profile. A path a profile does not list is not loaded++ // there, so it is not installed in that profile at all.++ std::vector<std::string> cra_profiles;++ if (switch_name == switches::kLoadExtension &&++ command_line_->HasSwitch("cra-load-extension-profiles")) {++ cra_profiles = base::SplitString(++ command_line_->GetSwitchValueASCII("cra-load-extension-profiles"), ",",++ base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);++ }++ const std::string cra_profile = profile_->GetBaseName().AsUTF8Unsafe();++ size_t cra_index = 0;+ while (t.GetNext()) {++ const size_t cra_path = cra_index++;++ if (cra_path < cra_profiles.size() && cra_profiles[cra_path] != "*") {++ const std::vector<std::string> allowed =++ base::SplitString(cra_profiles[cra_path], "|", base::TRIM_WHITESPACE,++ base::SPLIT_WANT_NONEMPTY);++ if (std::find(allowed.begin(), allowed.end(), cra_profile) ==++ allowed.end()) {++ continue;++ }++ }+ std::string extension_id;+ UnpackedInstaller::Create(profile_)->LoadFromCommandLine(+ base::FilePath(t.token_piece()), &extension_id,diff --git a/scripts/fetch-cef.sh b/scripts/fetch-cef.shindex 290ab04..5b94913 100755--- a/scripts/fetch-cef.sh+++ b/scripts/fetch-cef.sh@@ -13,7 +13,7 @@ CEF_VERSION="${CEF_VERSION:-156.0.15+gcf671c0+chromium-156.0.8078.80}"ARCH="${CEF_ARCH:-macosarm64}"NAME="cef_binary_${CEF_VERSION}_${ARCH}_minimal"# Bump the suffix (codecs2, …) when the build changes but CEF_VERSION does not.-CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs8}"+CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs9}"URL="${CEF_URL:-https://github.com/VictorKildahl/cra/releases/download/${CEF_RELEASE}/cef_binary_${ARCH}_minimal.tar.bz2}"mkdir -p vendor