From 3a556e7202b2df4dd26c8b1ed7885c6e1a24bec2 Mon Sep 17 00:00:00 2001 From: rangaNP Date: Mon, 23 Nov 2026 05:37:40 +0530 Subject: [PATCH] Make backups restorable and validate release publication --- .github/workflows/publish.yml | 11 +- Scripts/tests/test_validate_release.py | 115 ++++++++++++++++++ Scripts/validate-release.py | 68 +++++++++++ Sources/Early/BrowserApplication.swift | 67 +++++----- Sources/Early/BrowserSettingsView.swift | 5 +- Sources/Early/PortabilityViews.swift | 14 +++ Sources/EarlyCore/BrowserImportMapping.swift | 27 ++-- Sources/EarlyCore/BrowserWorkspace.swift | 4 +- Sources/EarlyCore/EarlyStateArchive.swift | 80 ++++++++---- Sources/EarlyCore/StateArchiveFiles.swift | 66 ++++++---- .../BackgroundArchiveApplicationTests.swift | 8 +- .../BrowserImportApplicationTests.swift | 39 ++++++ .../PortabilityApplicationTests.swift | 2 +- .../BrowserImportContextTests.swift | 2 +- Tests/EarlyCoreTests/BrowserImportTests.swift | 19 +++ Tests/EarlyCoreTests/StateArchiveTests.swift | 113 +++++++++++++++++ 16 files changed, 530 insertions(+), 110 deletions(-) create mode 100644 Scripts/tests/test_validate_release.py create mode 100644 Scripts/validate-release.py diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 7da828f..60ef241 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -28,18 +28,11 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - name: Read the release + - name: Validate the stable release id: release env: GH_TOKEN: ${{ github.token }} - run: | - tag="${GITHUB_REF_NAME}" - version="${tag#v}" - gh release download "$tag" --pattern SHA256SUMS --dir build - sha256="$(awk -v zip="Early-$version.zip" '$2 == zip { print $1 }' build/SHA256SUMS)" - [[ "$sha256" =~ ^[0-9a-f]{64}$ ]] || { echo "::error::No checksum for Early-$version.zip"; exit 1; } - echo "version=$version" >> "$GITHUB_OUTPUT" - echo "sha256=$sha256" >> "$GITHUB_OUTPUT" + run: python3 Scripts/validate-release.py >> "$GITHUB_OUTPUT" - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: earlybrowser/homebrew-tap diff --git a/Scripts/tests/test_validate_release.py b/Scripts/tests/test_validate_release.py new file mode 100644 index 0000000..c6f996c --- /dev/null +++ b/Scripts/tests/test_validate_release.py @@ -0,0 +1,115 @@ +# SPDX-License-Identifier: MPL-2.0 + +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import textwrap +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / "validate-release.py" + + +class ReleaseValidationTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory(prefix="Early release validation ") + self.addCleanup(temporary.cleanup) + self.directory = Path(temporary.name) + self.repo, self.tag, self.version = "owner/early-fixture", "v9.8.7", "9.8.7" + self.zip_name = f"Early-{self.version}.zip" + self.zip_bytes = b"fixture release archive" + self.checksum = hashlib.sha256(self.zip_bytes).hexdigest() + self.metadata = { + "tag_name": self.tag, "draft": False, "prerelease": False, "published_at": "2026-11-22T00:00:00Z", + "assets": [{"name": name, "state": "uploaded", "size": 20} + for name in (self.zip_name, "SHA256SUMS", "appcast.xml")], + } + (self.directory / self.zip_name).write_bytes(self.zip_bytes) + (self.directory / "SHA256SUMS").write_text(f"{self.checksum} {self.zip_name}\n", encoding="ascii") + gh = self.directory / "gh" + gh.write_text("#!/usr/bin/env python3\n" + textwrap.dedent("""\ + import os + from pathlib import Path + import shutil + import sys + + root = Path(os.environ["EARLY_RELEASE_FIXTURE"]) + args = sys.argv[1:] + repo, tag = os.environ["GITHUB_REPOSITORY"], os.environ["GITHUB_REF_NAME"] + if args == ["api", f"repos/{repo}/releases/tags/{tag}"]: + metadata = root / "release.json" + if not metadata.exists(): + sys.exit("release not found") + print(metadata.read_text()) + elif args[:3] == ["release", "download", tag] and args[args.index("--repo") + 1] == repo: + destination = Path(args[args.index("--dir") + 1]) + for index, arg in enumerate(args): + if arg == "--pattern": + shutil.copyfile(root / args[index + 1], destination / args[index + 1]) + (root / "downloaded").touch() + else: + sys.exit("unexpected gh call") + """)) + gh.chmod(0o700) + + def validate(self, event="workflow_dispatch", ref_type="tag", tag=None): + metadata = self.directory / "release.json" + if self.metadata is not None: + metadata.write_text(json.dumps(self.metadata)) + else: + metadata.unlink(missing_ok=True) + (self.directory / "downloaded").unlink(missing_ok=True) + env = {"PATH": f"{self.directory}{os.pathsep}{os.environ['PATH']}", + "GITHUB_REPOSITORY": self.repo, "GITHUB_REF_NAME": tag or self.tag, + "GITHUB_REF_TYPE": ref_type, "GITHUB_EVENT_NAME": event, "EARLY_RELEASE_FIXTURE": str(self.directory)} + return subprocess.run([sys.executable, str(SCRIPT)], env=env, capture_output=True, text=True) + + def assert_rejected(self, result, reason): + self.assertNotEqual(result.returncode, 0) + self.assertEqual(result.stdout, "") + self.assertIn(reason, result.stderr) + + def test_both_triggers_validate_the_same_stable_release(self): + for event in ("release", "workflow_dispatch", "workflow_dispatch"): + with self.subTest(event=event): + result = self.validate(event=event) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, f"version={self.version}\nsha256={self.checksum}\n") + + def test_rejects_draft_prerelease_unpublished_and_wrong_tag_before_downloading(self): + for field, invalid in (("draft", True), ("prerelease", True), ("published_at", None), ("tag_name", "v9.8.6")): + with self.subTest(field=field): + original = self.metadata[field] + self.metadata[field] = invalid + self.assert_rejected(self.validate(), "published stable") + self.assertFalse((self.directory / "downloaded").exists()) + self.metadata[field] = original + + def test_requires_a_published_release_for_the_exact_tag(self): + self.metadata = None + self.assert_rejected(self.validate(), "release not found") + self.assert_rejected(self.validate(ref_type="branch"), "Choose a stable release tag") + self.assert_rejected(self.validate(tag="v9.8.7-beta.1"), "Choose a stable release tag") + + def test_requires_all_uploaded_assets_for_the_selected_version(self): + assets = self.metadata["assets"] + for asset in assets: + with self.subTest(asset=asset["name"]): + self.metadata["assets"] = [entry for entry in assets if entry is not asset] + self.assert_rejected(self.validate(), asset["name"]) + self.assertFalse((self.directory / "downloaded").exists()) + self.metadata["assets"] = [{**assets[0], "name": "Early-9.8.6.zip"}, *assets[1:]] + self.assert_rejected(self.validate(), self.zip_name) + + def test_rejects_missing_malformed_duplicate_and_mismatched_checksums(self): + for text in ("", f"invalid {self.zip_name}\n", f"{self.checksum} {self.zip_name}\n" * 2, + f"{self.checksum} Early-9.8.6.zip\n"): + with self.subTest(text=text): + (self.directory / "SHA256SUMS").write_text(text, encoding="ascii") + self.assert_rejected(self.validate(), "exactly one valid checksum") + (self.directory / "SHA256SUMS").write_text(f"{'0' * 64} {self.zip_name}\n", encoding="ascii") + self.assert_rejected(self.validate(), "does not match the published ZIP") diff --git a/Scripts/validate-release.py b/Scripts/validate-release.py new file mode 100644 index 0000000..ded1662 --- /dev/null +++ b/Scripts/validate-release.py @@ -0,0 +1,68 @@ +# SPDX-License-Identifier: MPL-2.0 + +"""Validate the release selected by either Homebrew workflow trigger.""" + +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + + +def find_release(repo, tag, zip_name): + response = subprocess.check_output(["gh", "api", f"repos/{repo}/releases/tags/{tag}"]) + release = json.loads(response) + if (not isinstance(release, dict) or release.get("tag_name") != tag or release.get("draft") is not False + or release.get("prerelease") is not False or not release.get("published_at")): + raise ValueError(f"{tag} must be a published stable GitHub release.") + + for name in (zip_name, "SHA256SUMS", "appcast.xml"): + matching = [asset for asset in release["assets"] if asset["name"] == name] + if len(matching) != 1 or matching[0]["state"] != "uploaded" or matching[0]["size"] <= 0: + raise ValueError(f"{tag} needs an uploaded {name} asset.") + + +def verified_checksum(directory, zip_name): + manifest = (directory / "SHA256SUMS").read_text(encoding="ascii") + rows = [line.split() for line in manifest.splitlines() if line.strip()] + matches = [row for row in rows if row[-1].removeprefix("*") == zip_name] + if len(matches) != 1 or len(matches[0]) != 2 or not re.fullmatch(r"[0-9a-fA-F]{64}", matches[0][0]): + raise ValueError(f"SHA256SUMS must contain exactly one valid checksum for {zip_name}.") + expected = matches[0][0].lower() + + digest = hashlib.sha256() + with (directory / zip_name).open("rb") as archive: + for chunk in iter(lambda: archive.read(1024 * 1024), b""): + digest.update(chunk) + if digest.hexdigest() != expected: + raise ValueError(f"The checksum for {zip_name} does not match the published ZIP.") + return expected + + +def main(): + try: + tag = os.environ["GITHUB_REF_NAME"] + repo = os.environ["GITHUB_REPOSITORY"] + if os.environ["GITHUB_REF_TYPE"] != "tag" or not re.fullmatch(r"v[0-9]+\.[0-9]+\.[0-9]+", tag): + raise ValueError("Choose a stable release tag such as v1.2.3.") + version = tag[1:] + zip_name = f"Early-{version}.zip" + find_release(repo, tag, zip_name) + with tempfile.TemporaryDirectory(prefix="early-release-") as directory: + subprocess.run(["gh", "release", "download", tag, "--repo", repo, "--dir", directory, + "--pattern", "SHA256SUMS", "--pattern", zip_name], check=True, stdout=sys.stderr) + checksum = verified_checksum(Path(directory), zip_name) + except (KeyError, TypeError, ValueError, OSError, subprocess.CalledProcessError) as error: + print(f"Release validation failed. {error}", file=sys.stderr) + return 1 + + print(f"version={version}") + print(f"sha256={checksum}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/Sources/Early/BrowserApplication.swift b/Sources/Early/BrowserApplication.swift index 73a0196..4fe634a 100644 --- a/Sources/Early/BrowserApplication.swift +++ b/Sources/Early/BrowserApplication.swift @@ -726,11 +726,14 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { captureWorkspace() guard let workspace else { throw EarlyStateArchive.Problem.invalid } let settings = preferences?.portableSettings - try await BackgroundFileIO.run { try EarlyStateArchive.write(workspace: workspace, settings: settings, to: url) } + let input = input + try await BackgroundFileIO.run { try EarlyStateArchive.write(workspace: workspace, settings: settings, to: url, using: input) } } - @ObservationIgnored var archiveBackupWriter: @Sendable (BrowserWorkspace, PortableSettings?, URL) async throws -> URL = { workspace, settings, directory in - try await BackgroundFileIO.run { try EarlyStateArchive.backup(workspace: workspace, settings: settings, in: directory, retaining: 5) } + @ObservationIgnored var archiveBackupWriter: @Sendable (BrowserWorkspace, PortableSettings?, URL, NavigationInput) async throws -> URL = { workspace, settings, directory, input in + try await BackgroundFileIO.run { + try EarlyStateArchive.backup(workspace: workspace, settings: settings, in: directory, using: input) + } } /// The password, privacy and update settings a file would change here. @@ -772,32 +775,18 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { captureWorkspace() guard let current = workspace else { throw BrowserImportProblem.invalid } guard try await journal.entries().count < 128 else { throw BrowserImportProblem.capacity } - let validationInput = input - var candidate = try await Task.detached { + let validationInput = input, settings = preferences?.portableSettings + var candidate = try await BackgroundFileIO.run { try document.candidate(into: current, selecting: selected, destinations: destinations, flattenDeepFolders: flatten, - collectionTargets: collectionTargets, using: validationInput) - }.value + collectionTargets: collectionTargets, resultSettings: settings, using: validationInput) + } try Task.checkCancellation() // A recoverable backup must be durable before the first history insertion. - let backupDirectory = backupsDirectory! + guard let backupDirectory = backupsDirectory else { throw CocoaError(.fileWriteUnknown) } let backupBatchID = candidate.batch.id - let backup = try await Task.detached { - try FileManager.default.createDirectory(at: backupDirectory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) - let formatter = DateFormatter() - formatter.locale = Locale(identifier: "en_US_POSIX") - formatter.dateFormat = "yyyy-MM-dd 'at' HH.mm.ss" - let url = backupDirectory.appendingPathComponent("Before Import \(formatter.string(from: Date())) \(backupBatchID).json") - try EarlyStateArchive(workspace: current, settings: nil).encoded().write(to: url, options: .atomic) - try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) - let file = try FileHandle(forWritingTo: url) - defer { try? file.close() } - try file.synchronize() - let backups = try FileManager.default.contentsOfDirectory(at: backupDirectory, includingPropertiesForKeys: nil) - .filter { $0.lastPathComponent.hasPrefix("Before Import ") && $0.pathExtension == "json" } - .sorted { $0.lastPathComponent < $1.lastPathComponent } - for old in backups.dropLast(5) where old != url { try FileManager.default.removeItem(at: old) } - return url - }.value + let backup = try await BackgroundFileIO.run { + try EarlyStateArchive.backup(workspace: current, settings: nil, in: backupDirectory, id: backupBatchID, using: validationInput) + } try await journal.write(.init(batch: candidate.batch, state: .importing)) batch = candidate.batch var importedVisits = 0 @@ -808,9 +797,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { } try Task.checkCancellation() // Incorporate any page metadata/selection changes that arrived while reading. - captureWorkspace() - guard let latest = workspace else { throw BrowserImportProblem.invalid } - let rebased = try candidate.adding(to: latest, using: input) + let rebased = try await rebaseBrowserImport(candidate) candidate.batch = candidate.batch.adjustedPositions(in: rebased) try await journal.write(.init(batch: candidate.batch, state: .importing)) batch = candidate.batch @@ -818,8 +805,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { guard await persistence?.flush() == true else { throw SessionError.database(persistence?.error ?? "Couldn’t save the import.") } // The marker and organization are now durable. Never roll history back after this point. batch = nil - captureWorkspace() - let live = (try? candidate.adding(to: workspace ?? latest, using: input)) ?? rebased + let live = (try? await rebaseBrowserImport(candidate)) ?? rebased workspace = live for session in live.sessions { let owners = visibleModels.filter { $0.coordinator.profileID == session.profileID } @@ -851,6 +837,19 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { } } + private func rebaseBrowserImport(_ candidate: BrowserImportCandidate) async throws -> BrowserWorkspace { + let input = input + for _ in 0..<8 { + captureWorkspace() + guard let current = workspace else { throw BrowserImportProblem.invalid } + let settings = preferences?.portableSettings + let merged = try await BackgroundFileIO.run { try candidate.adding(to: current, resultSettings: settings, using: input) } + captureWorkspace() + if workspace == current, preferences?.portableSettings == settings { return merged } + } + throw BrowserImportProblem.unsupported("Your browsing setup kept changing during the import. Try again in a moment.") + } + func undoBrowserImport(_ requested: BrowserImportBatch) async -> ImportOutcome { guard canEditProfiles, let journal = browserImportJournal else { return .init(message: "Early can’t undo an import right now.", succeeded: false) @@ -934,12 +933,12 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { captureWorkspace() guard let current = workspace else { return .init(message: EarlyStateArchive.Problem.invalid.message, succeeded: false) } let settings = preferences.portableSettings + let importedSettings = includeSettings ? archive.settings : nil + let resultSettings = importedSettings.map { preferences.portableSettings(applying: $0, includingSensitive: includeSensitiveSettings) } ?? settings let result: EarlyStateArchive.ImportResult do { result = try await BackgroundFileIO.run { - let result = try archive.merged(into: current, mode: mode, using: validation) - try Task.checkCancellation() - return result + try archive.merged(into: current, mode: mode, resultSettings: resultSettings, using: validation) } } catch is CancellationError { return .init(message: "Import cancelled. Nothing was changed.", succeeded: false) } catch { return .init(message: (error as? EarlyStateArchive.Problem ?? .invalid).message, succeeded: false) } @@ -949,7 +948,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate { let backup: URL do { guard let directory = backupsDirectory else { throw CocoaError(.fileWriteUnknown) } - backup = try await archiveBackupWriter(current, settings, directory) + backup = try await archiveBackupWriter(current, settings, directory, validation) } catch is CancellationError { return .init(message: "Import cancelled. Nothing was changed.", succeeded: false) } catch { return .init(message: "Nothing was imported, because a backup of what you have couldn’t be saved. \(error.localizedDescription)", succeeded: false) diff --git a/Sources/Early/BrowserSettingsView.swift b/Sources/Early/BrowserSettingsView.swift index 29a6714..e46dc78 100644 --- a/Sources/Early/BrowserSettingsView.swift +++ b/Sources/Early/BrowserSettingsView.swift @@ -637,7 +637,10 @@ private struct ProfileEditorSheet: View { if let profile = request.profile { if application.editProfile(profile.id, name: name, color: color) { onSave(profile.id) } else { error = "This profile could not be saved. Please try again." } - } else if let id = application.createProfile(name: name, color: color) { onSave(id) } + } else if application.workspace?.canCreateProfile == false { + error = "You can create up to \(EarlyStateArchive.maximumProfiles) profiles." + } + else if let id = application.createProfile(name: name, color: color) { onSave(id) } else { error = "This profile could not be created. Please try again." } } } diff --git a/Sources/Early/PortabilityViews.swift b/Sources/Early/PortabilityViews.swift index e445370..3416402 100644 --- a/Sources/Early/PortabilityViews.swift +++ b/Sources/Early/PortabilityViews.swift @@ -53,6 +53,7 @@ struct StatePortabilityCard: View { @Bindable var application: EarlyAppDelegate @State private var preview: StateImportPreview? @State private var outcome: EarlyAppDelegate.ImportOutcome? + @State private var sessionRecoveryFolder: URL? @State private var transfer: Task? @State private var transferID: UUID? @@ -86,6 +87,12 @@ struct StatePortabilityCard: View { Button("Show Backup in Finder") { NSWorkspace.shared.activateFileViewerSelecting([backup]) } .buttonStyle(.link).font(.caption) } + if let folder = sessionRecoveryFolder { + Text("For a local recovery copy, quit Early and copy this folder. Restore the folder to the same location with Early closed.") + .font(.caption).foregroundStyle(.secondary) + Button("Show Session Folder") { NSWorkspace.shared.open(folder) } + .buttonStyle(.link).font(.caption) + } } } .sheet(item: $preview) { preview in @@ -116,12 +123,18 @@ struct StatePortabilityCard: View { transferID = request transfer = Task { let result: EarlyAppDelegate.ImportOutcome + var recoveryFolder: URL? do { try await application.exportState(to: url) result = .init(message: "Exported to “\(url.lastPathComponent)”.", succeeded: true) } catch is CancellationError { return } + catch let problem as EarlyStateArchive.Problem where problem.isCapacityLimit { + result = .init(message: "Couldn’t export. \(problem.message)", succeeded: false) + recoveryFolder = application.storageURL?.deletingLastPathComponent() + } catch { result = .init(message: "Couldn’t export. \(error.localizedDescription)", succeeded: false) } guard transferID == request else { return } + sessionRecoveryFolder = recoveryFolder outcome = result; transfer = nil; transferID = nil } } @@ -135,6 +148,7 @@ struct StatePortabilityCard: View { panel.prompt = "Review" panel.message = "Choose a file exported from Early. You’ll see what it contains before anything changes." present(panel) { url in + sessionRecoveryFolder = nil let request = UUID() transferID = request transfer = Task { diff --git a/Sources/EarlyCore/BrowserImportMapping.swift b/Sources/EarlyCore/BrowserImportMapping.swift index a57797b..369155d 100644 --- a/Sources/EarlyCore/BrowserImportMapping.swift +++ b/Sources/EarlyCore/BrowserImportMapping.swift @@ -41,7 +41,8 @@ public struct BrowserImportCandidate: Sendable { /// Rebase the additive delta onto live state after disk I/O. Page metadata, /// selections and unrelated windows may have changed while saving. - public func adding(to current: BrowserWorkspace, using input: NavigationInput = NavigationInput()) throws -> BrowserWorkspace { + public func adding(to current: BrowserWorkspace, resultSettings: PortableSettings? = nil, + using input: NavigationInput = NavigationInput()) throws -> BrowserWorkspace { var merged = current let existingProfiles = Set(current.profiles.map(\.id)) for profile in workspace.profiles where !existingProfiles.contains(profile.id) { @@ -74,10 +75,17 @@ public struct BrowserImportCandidate: Sendable { merged.sessions[index] = root } merged.browserImportBatchIDs = (current.browserImportBatchIDs ?? []) + [batch.id] - try merged.validate(using: input); return merged + try validateImportedWorkspace(merged, settings: resultSettings, using: input) + return merged } } +private func validateImportedWorkspace(_ workspace: BrowserWorkspace, settings: PortableSettings?, using input: NavigationInput) throws { + try workspace.validate(using: input) + do { _ = try EarlyStateArchive(workspace: workspace, settings: settings).encoded(using: input) } + catch let problem as EarlyStateArchive.Problem where problem.isCapacityLimit { throw BrowserImportProblem.capacity } +} + public extension BrowserImportDocument { /// Destination keys are source Spaces, or the source profile for loose items. var destinationGroups: [BrowserImportNode] { nodes.filter { $0.kind == .profile || $0.kind == .space } } @@ -97,13 +105,13 @@ public extension BrowserImportDocument { func candidate(into current: BrowserWorkspace, selecting selected: Set, destinations: [String: BrowserImportDestination], flattenDeepFolders: Bool = false, - collectionTargets: [String: Set] = [:], + collectionTargets: [String: Set] = [:], resultSettings: PortableSettings? = nil, using input: NavigationInput = NavigationInput()) throws -> BrowserImportCandidate { try validate() if !collections.isEmpty { let resolved = try resolvingCollections(selecting: selected, targets: collectionTargets, destinations: destinations) return try resolved.document.candidate(into: current, selecting: resolved.selected, destinations: destinations, - flattenDeepFolders: flattenDeepFolders, using: input) + flattenDeepFolders: flattenDeepFolders, resultSettings: resultSettings, using: input) } let included = included(selected) guard !selected.isEmpty else { throw BrowserImportProblem.invalid } @@ -161,7 +169,7 @@ public extension BrowserImportDocument { profile = id } else if let id = profileMap[profileKey] { profile = id } else { - guard result.workspace.profiles.count < EarlyStateArchive.maximumProfiles else { throw BrowserImportProblem.capacity } + guard result.workspace.canCreateProfile else { throw BrowserImportProblem.capacity } let name = EarlyStateArchive.uniqueName(destination.profileName, in: result.workspace.profiles) guard let id = result.workspace.createProfile(name: name, color: sourceProfile.color ?? .blue) else { throw BrowserImportProblem.invalid } profileMap[profileKey] = id; profile = id @@ -243,14 +251,7 @@ public extension BrowserImportDocument { guard result.history.values.allSatisfy({ $0.count <= Self.maximumVisits }) else { throw BrowserImportProblem.capacity } result.batch.historyProfiles = result.history.keys.sorted { $0.uuidString < $1.uuidString } result.workspace.browserImportBatchIDs = (current.browserImportBatchIDs ?? []) + [result.batch.id] - try result.workspace.validate(using: input) - let windows = result.workspace.sessions.flatMap { [$0] + $0.additionalWindows } - guard result.workspace.profiles.count <= EarlyStateArchive.maximumProfiles, - windows.reduce(0, { $0 + $1.tabs.count }) <= EarlyStateArchive.maximumTabs else { throw BrowserImportProblem.capacity } - let archive = EarlyStateArchive(workspace: result.workspace, settings: nil) - let encoded = try archive.encoded() - guard encoded.count <= EarlyStateArchive.maximumSize else { throw BrowserImportProblem.capacity } - _ = try EarlyStateArchive.decode(encoded, using: input) + try validateImportedWorkspace(result.workspace, settings: resultSettings, using: input) return result } diff --git a/Sources/EarlyCore/BrowserWorkspace.swift b/Sources/EarlyCore/BrowserWorkspace.swift index a2e4723..3067025 100644 --- a/Sources/EarlyCore/BrowserWorkspace.swift +++ b/Sources/EarlyCore/BrowserWorkspace.swift @@ -76,9 +76,11 @@ public struct BrowserWorkspace: Codable, Equatable, Sendable { return result } + public var canCreateProfile: Bool { profiles.count < EarlyStateArchive.maximumProfiles } + @discardableResult public mutating func createProfile(name: String, color: BrowserSpace.Color = .blue) -> UUID? { - guard let name = BrowserSpace.normalizedName(name), + guard canCreateProfile, let name = BrowserSpace.normalizedName(name), !profiles.contains(where: { $0.name.lowercased() == name.lowercased() }) else { return nil } let profile = BrowserProfile(name: name, color: color) let space = BrowserSpace(profileID: profile.id, name: name, color: color) diff --git a/Sources/EarlyCore/EarlyStateArchive.swift b/Sources/EarlyCore/EarlyStateArchive.swift index e02a1e7..9b81c85 100644 --- a/Sources/EarlyCore/EarlyStateArchive.swift +++ b/Sources/EarlyCore/EarlyStateArchive.swift @@ -69,17 +69,30 @@ public extension BrowserPreferences { } } - /// Uses what the file has that Early knows, leaving everything else as it - /// is: the sensitive settings too only when `includingSensitive`. - func apply(_ settings: PortableSettings, includingSensitive: Bool = false) { + /// The settings an import will leave, including the size of the next archive. + func portableSettings(applying settings: PortableSettings, includingSensitive: Bool = false) -> PortableSettings { + var result = portableSettings let sensitive = Set(Self.sensitiveToggles.map(\.name)) - for (name, path) in Self.portableToggles where includingSensitive || !sensitive.contains(name) { - if let value = settings.toggles[name], self[keyPath: path] != value { self[keyPath: path] = value } + for (name, _) in Self.portableToggles where includingSensitive || !sensitive.contains(name) { + if let value = settings.toggles[name] { result.toggles[name] = value } } - if let value = settings.appearance.flatMap(Appearance.init(rawValue:)), value != appearance { appearance = value } - if let value = settings.searchEngine.flatMap(SearchEngine.init(rawValue:)), value != searchEngine { searchEngine = value } - if let value = settings.sidebarWidth, value.isFinite { sidebarWidth = value } - if let value = settings.shortcuts, value.isUsable, value != shortcuts { shortcuts = value } + if let value = settings.appearance.flatMap(Appearance.init(rawValue:)) { result.appearance = value.rawValue } + if let value = settings.searchEngine.flatMap(SearchEngine.init(rawValue:)) { result.searchEngine = value.rawValue } + if let value = settings.sidebarWidth, value.isFinite { result.sidebarWidth = SidebarWidth.clamped(value) } + if let value = settings.shortcuts, value.isUsable { result.shortcuts = value } + return result + } + + /// Uses the same allowlist when previewing and when applying an import. + func apply(_ settings: PortableSettings, includingSensitive: Bool = false) { + let result = portableSettings(applying: settings, includingSensitive: includingSensitive) + for (name, path) in Self.portableToggles { + if let value = result.toggles[name], self[keyPath: path] != value { self[keyPath: path] = value } + } + if let value = result.appearance.flatMap(Appearance.init(rawValue:)), value != appearance { appearance = value } + if let value = result.searchEngine.flatMap(SearchEngine.init(rawValue:)), value != searchEngine { searchEngine = value } + if let value = result.sidebarWidth, value != sidebarWidth { sidebarWidth = value } + if let value = result.shortcuts, value != shortcuts { shortcuts = value } } } @@ -91,7 +104,7 @@ public struct EarlyStateArchive: Codable, Equatable, Sendable { public static let formatName = "early-state" public static let currentVersion = 1 public static let maximumSize = 16 * 1024 * 1024 - public static let maximumProfiles = 32 + public static let maximumProfiles = 64 public static let maximumTabs = 20_000 public var format: String @@ -100,12 +113,17 @@ public struct EarlyStateArchive: Codable, Equatable, Sendable { public var settings: PortableSettings? public var workspace: BrowserWorkspace - public enum Problem: Error, Equatable, Sendable { - case tooLarge, notAnArchive, newerVersion, invalid + public enum Problem: LocalizedError, Equatable, Sendable { + case tooLarge, tooManyProfiles, tooManyTabs, notAnArchive, newerVersion, invalid + + public var isCapacityLimit: Bool { self == .tooLarge || self == .tooManyProfiles || self == .tooManyTabs } + public var errorDescription: String? { message } public var message: String { switch self { - case .tooLarge: "The file is too large to be an Early export." + case .tooLarge: "Early archives can be up to \(EarlyStateArchive.maximumSize / (1024 * 1024)) MiB." + case .tooManyProfiles: "Early archives can hold up to \(EarlyStateArchive.maximumProfiles) profiles." + case .tooManyTabs: "Early archives can hold up to \(EarlyStateArchive.maximumTabs.formatted()) tab records across windows." case .notAnArchive: "The file isn’t an Early export." case .newerVersion: "The file was exported by a newer version of Early. Update Early to import it." case .invalid: "The file is damaged or incomplete, so nothing was imported." @@ -129,11 +147,29 @@ public struct EarlyStateArchive: Codable, Equatable, Sendable { self.workspace = copy } - public func encoded() throws -> Data { + public func encoded(using input: NavigationInput = NavigationInput()) throws -> Data { + try Task.checkCancellation() + try Self.validateWorkspace(workspace, using: input) + guard format == Self.formatName, version >= 1 else { throw Problem.notAnArchive } + guard version <= Self.currentVersion else { throw Problem.newerVersion } + try Task.checkCancellation() let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] encoder.dateEncodingStrategy = .iso8601 - return try encoder.encode(self) + let data = try encoder.encode(self) + guard data.count <= Self.maximumSize else { throw Problem.tooLarge } + try Task.checkCancellation() + return data + } + + private static func validateWorkspace(_ workspace: BrowserWorkspace, using input: NavigationInput) throws { + guard workspace.profiles.count <= maximumProfiles else { throw Problem.tooManyProfiles } + let tabCount = workspace.sessions.reduce(into: 0) { count, root in + count += root.tabs.count + for window in root.additionalWindows { count += window.tabs.count } + } + guard tabCount <= maximumTabs else { throw Problem.tooManyTabs } + guard (try? workspace.validate(using: input)) != nil else { throw Problem.invalid } } /// Reads a file, checking its size, format, version, structure and @@ -147,10 +183,7 @@ public struct EarlyStateArchive: Codable, Equatable, Sendable { let version = header.version, version >= 1 else { throw Problem.notAnArchive } guard version <= currentVersion else { throw Problem.newerVersion } guard let archive = try? decoder.decode(Self.self, from: data) else { throw Problem.invalid } - let windows = archive.workspace.sessions.flatMap { [$0] + $0.additionalWindows } - guard archive.workspace.profiles.count <= maximumProfiles, - windows.reduce(0, { $0 + $1.tabs.count }) <= maximumTabs, - (try? archive.workspace.validate(using: input)) != nil else { throw Problem.invalid } + try validateWorkspace(archive.workspace, using: input) return archive } @@ -223,11 +256,15 @@ public struct EarlyStateArchive: Codable, Equatable, Sendable { /// The workspace after importing, checked in full. Every Space, folder, /// tab and split gets a new identity, so nothing can collide with what is /// already here; no tab is selected, so nothing loads until it's chosen. - public func merged(into current: BrowserWorkspace, mode: ImportMode, + public func merged(into current: BrowserWorkspace, mode: ImportMode, resultSettings: PortableSettings? = nil, using input: NavigationInput = NavigationInput()) throws -> ImportResult { - guard (try? workspace.validate(using: input)) != nil else { throw Problem.invalid } + try Self.validateWorkspace(workspace, using: input) + guard current.profiles.count <= Self.maximumProfiles else { throw Problem.tooManyProfiles } var draft = current let matches = mode == .replaceMatching ? self.matches(in: current) : [:] + guard current.profiles.count + workspace.profiles.count - matches.count <= Self.maximumProfiles else { + throw Problem.tooManyProfiles + } var map = IdentityMap() var result = ImportResult(workspace: current, profiles: [], replaced: [], openProfiles: []) for profile in workspace.profiles { @@ -249,6 +286,7 @@ public struct EarlyStateArchive: Codable, Equatable, Sendable { if workspace.openProfileIDs.contains(profile.id) { result.openProfiles.append(target) } } guard (try? draft.validate(using: input)) != nil else { throw Problem.invalid } + _ = try EarlyStateArchive(workspace: draft, settings: resultSettings).encoded(using: input) result.workspace = draft return result } diff --git a/Sources/EarlyCore/StateArchiveFiles.swift b/Sources/EarlyCore/StateArchiveFiles.swift index c8d6311..631d169 100644 --- a/Sources/EarlyCore/StateArchiveFiles.swift +++ b/Sources/EarlyCore/StateArchiveFiles.swift @@ -3,6 +3,8 @@ import Foundation extension EarlyStateArchive { + private static let backupLock = NSLock() + /// These operations are synchronous worker bodies; their app callers use /// BackgroundFileIO.run so encoding, decoding and disk access stay off UI. public static func read(from url: URL, using input: NavigationInput) throws -> Self { @@ -17,35 +19,49 @@ extension EarlyStateArchive { return result } - public static func write(workspace: BrowserWorkspace, settings: PortableSettings?, to url: URL) throws { - let data = try EarlyStateArchive(workspace: workspace, settings: settings).encoded() - guard data.count <= maximumSize else { throw Problem.tooLarge } - try Task.checkCancellation() + public static func write(workspace: BrowserWorkspace, settings: PortableSettings?, to url: URL, + using input: NavigationInput = NavigationInput()) throws { + let data = try EarlyStateArchive(workspace: workspace, settings: settings).encoded(using: input) try BackgroundFileIO.writeSynchronously(data, to: url) } public static func backup(workspace: BrowserWorkspace, settings: PortableSettings?, in directory: URL, - retaining limit: Int) throws -> URL { - try Task.checkCancellation() - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, - attributes: [.posixPermissions: 0o700]) - let formatter = DateFormatter() - formatter.locale = Locale(identifier: "en_US_POSIX") - formatter.dateFormat = "yyyy-MM-dd 'at' HH.mm.ss" - let file = directory.appendingPathComponent("Before Import \(formatter.string(from: Date())) \(UUID()).json") - try write(workspace: workspace, settings: settings, to: file) - let backups = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.contentModificationDateKey]) - .filter { $0.lastPathComponent.hasPrefix("Before Import ") && $0.pathExtension == "json" } - .sorted { - // Several imports can finish in one displayed second. UUID - // suffixes do not express age; always retain this new backup. - if $0.lastPathComponent == file.lastPathComponent { return false } - if $1.lastPathComponent == file.lastPathComponent { return true } - let a = (try? $0.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast - let b = (try? $1.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast - return a == b ? $0.lastPathComponent < $1.lastPathComponent : a < b + retaining limit: Int = 5, id: UUID = UUID(), + using input: NavigationInput = NavigationInput()) throws -> URL { + let archive = EarlyStateArchive(workspace: workspace, settings: settings) + let data = try archive.encoded(using: input) + // Both import paths share one directory. Finish each write and prune + // together so a concurrent backup cannot race its retention pass. + return try backupLock.withLock { + try Task.checkCancellation() + let files = FileManager.default + try files.createDirectory(at: directory, withIntermediateDirectories: true, + attributes: [.posixPermissions: 0o700]) + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.dateFormat = "yyyy-MM-dd 'at' HH.mm.ss" + let file = directory.appendingPathComponent("Before Import \(formatter.string(from: archive.exportedAt)) \(id).json") + try BackgroundFileIO.writeSynchronously(data, to: file) + try pruneBackups(in: directory, keeping: file, retaining: limit) + return file + } + } + + private static func pruneBackups(in directory: URL, keeping newest: URL, retaining limit: Int) throws { + let files = FileManager.default + let keys: Set = [.contentModificationDateKey, .isRegularFileKey, .isSymbolicLinkKey] + // Earlier versions used no suffix or four hex digits. Both current + // import paths use full UUIDs. Leave unrelated entries and links alone. + let namePattern = #"\ABefore Import [0-9]{4}-[0-9]{2}-[0-9]{2} at [0-9]{2}\.[0-9]{2}\.[0-9]{2}(?: (?:[0-9A-Fa-f]{4}|[0-9A-Fa-f]{8}(?:-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}))?\.json\z"# + let earlier = try files.contentsOfDirectory(at: directory, includingPropertiesForKeys: Array(keys)) + .compactMap { url -> (url: URL, modified: Date)? in + guard url.lastPathComponent != newest.lastPathComponent, + url.lastPathComponent.range(of: namePattern, options: .regularExpression) != nil, + let values = try? url.resourceValues(forKeys: keys), values.isRegularFile == true, + values.isSymbolicLink == false, let modified = values.contentModificationDate else { return nil } + return (url, modified) } - for old in backups.dropLast(max(1, limit)) { try? FileManager.default.removeItem(at: old) } - return file + .sorted { ($0.modified, $0.url.lastPathComponent) > ($1.modified, $1.url.lastPathComponent) } + for backup in earlier.dropFirst(max(1, limit) - 1) { try? files.removeItem(at: backup.url) } } } diff --git a/Tests/EarlyBrowserTests/BackgroundArchiveApplicationTests.swift b/Tests/EarlyBrowserTests/BackgroundArchiveApplicationTests.swift index 489f242..8877359 100644 --- a/Tests/EarlyBrowserTests/BackgroundArchiveApplicationTests.swift +++ b/Tests/EarlyBrowserTests/BackgroundArchiveApplicationTests.swift @@ -73,9 +73,9 @@ struct BackgroundArchiveApplicationTests { _ = try await open("one", in: model) let archive = try #require(app.stateArchive()) let writer = app.archiveBackupWriter - app.archiveBackupWriter = { workspace, settings, directory in + app.archiveBackupWriter = { workspace, settings, directory, input in await gate.pauseFirst() - return try await writer(workspace, settings, directory) + return try await writer(workspace, settings, directory, input) } let operation = Task { await app.importState(archive, mode: .addProfiles, includeSettings: false) } try await wait(gate) @@ -102,9 +102,9 @@ struct BackgroundArchiveApplicationTests { let tab = try await open("one", in: model) let view = try #require(model.webViews.existingView(for: tab)), archive = try #require(app.stateArchive()) let writer = app.archiveBackupWriter - app.archiveBackupWriter = { workspace, settings, directory in + app.archiveBackupWriter = { workspace, settings, directory, input in await gate.pauseFirst() - return try await writer(workspace, settings, directory) + return try await writer(workspace, settings, directory, input) } let operation = Task { await app.importState(archive, mode: .replaceMatching, includeSettings: true) } try await wait(gate) diff --git a/Tests/EarlyBrowserTests/BrowserImportApplicationTests.swift b/Tests/EarlyBrowserTests/BrowserImportApplicationTests.swift index a5fdc14..ceff79b 100644 --- a/Tests/EarlyBrowserTests/BrowserImportApplicationTests.swift +++ b/Tests/EarlyBrowserTests/BrowserImportApplicationTests.swift @@ -47,6 +47,45 @@ struct BrowserImportApplicationTests { let session = app.workspace!.sessions[0] return ["profile": .init(profileID: session.profileID, profileName: "Default", spaceID: session.activeSpaceID, spaceName: "Personal")] } + + @Test func browserImportKeepsTheNewBackupAndFourEarlierBackupsByModificationTime() async throws { + let fixture = Fixture() + await fixture.start() + let app = fixture.application, files = FileManager.default + let directory = try #require(app.backupsDirectory) + try files.createDirectory(at: directory, withIntermediateDirectories: true) + let before = try #require(app.stateArchive()) + let bytes = try before.encoded(using: app.browserImportValidation()) + let timestamp = Date().addingTimeInterval(600) + func file(_ number: Int) -> URL { + let suffix = String(format: "%012d", number) + return directory.appendingPathComponent("Before Import 9999-01-01 at 10.20.30 00000000-0000-0000-0000-\(suffix).json") + } + // All six filenames have the same displayed second. The UUID order + // differs from disk recency, and the retention cutoff has a tie. + for (number, offset) in [(90, 0.0), (95, 0.1), (10, 0.1), (20, 0.2), (30, 0.3), (40, 0.4)] { + let path = file(number) + try bytes.write(to: path) + try files.setAttributes([.modificationDate: timestamp.addingTimeInterval(offset)], ofItemAtPath: path.path) + } + let note = directory.appendingPathComponent("Before Import notes.json") + try Data("unrelated".utf8).write(to: note) + let folder = file(80) + try files.createDirectory(at: folder, withIntermediateDirectories: false) + let link = file(81) + try files.createSymbolicLink(at: link, withDestinationURL: note) + + let document = source() + let result = await app.importBrowser(document, selected: document.initiallySelected, destinations: destinations(app), flatten: false) + try #require(result.succeeded, "\(result.message)") + let backup = try #require(result.backup) + let expected = Set(([95, 20, 30, 40].map(file) + [backup, note, folder, link]).map(\.lastPathComponent)) + #expect(Set(try files.contentsOfDirectory(atPath: directory.path)) == expected) + #expect(try await app.readStateArchive(at: backup).workspace == before.workspace) + #expect(try Data(contentsOf: note) == Data("unrelated".utf8)) + await fixture.cleanup() + } + @Test func importingPreservesLiveWebViewsSelectionsMediaAndSiblingWindows() async throws { let fixture = Fixture(); await fixture.start() let app = fixture.application, model = try #require(fixture.application.model) diff --git a/Tests/EarlyBrowserTests/PortabilityApplicationTests.swift b/Tests/EarlyBrowserTests/PortabilityApplicationTests.swift index 7984fd5..56ef7a2 100644 --- a/Tests/EarlyBrowserTests/PortabilityApplicationTests.swift +++ b/Tests/EarlyBrowserTests/PortabilityApplicationTests.swift @@ -73,7 +73,7 @@ struct PortabilityApplicationTests { #expect(privateWindow.openLocations([two])) fixture.preferences.searchEngine = .bing let archive = try #require(app.stateArchive()) - let text = try #require(String(data: try archive.encoded(), encoding: .utf8)) + let text = try #require(String(data: try archive.encoded(using: input), encoding: .utf8)) #expect(text.contains("fixture/one") && !text.contains("fixture/two"), "Private windows are never exported") #expect(archive.workspace.profiles.count == 1 && archive.settings?.searchEngine == "bing") fixture.preferences.searchEngine = .google diff --git a/Tests/EarlyCoreTests/BrowserImportContextTests.swift b/Tests/EarlyCoreTests/BrowserImportContextTests.swift index d707fa0..f25d412 100644 --- a/Tests/EarlyCoreTests/BrowserImportContextTests.swift +++ b/Tests/EarlyCoreTests/BrowserImportContextTests.swift @@ -190,7 +190,7 @@ struct BrowserImportContextTests { } @Test func profileCapacityIsCheckedWithoutCombiningContextsOrChangingInput() throws { var doc = BrowserImportDocument(source: "Many contexts") - for number in 0..<36 { + for number in 0.. BrowserWorkspace { + var workspace = BrowserWorkspace() + for index in 1.. Data { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + return try encoder.encode(EarlyStateArchive(workspace: workspace, settings: nil)) + } + + @Test(arguments: [32, 33, EarlyStateArchive.maximumProfiles]) + func profileBoundsRoundTripThroughTheFileWriter(count: Int) throws { + var workspace = try workspace(withProfiles: count) + let file = FileManager.default.temporaryDirectory.appendingPathComponent("EarlyProfiles-\(UUID()).json") + defer { try? FileManager.default.removeItem(at: file) } + try EarlyStateArchive.write(workspace: workspace, settings: nil, to: file) + #expect(try EarlyStateArchive.read(from: file, using: input).workspace == workspace) + if count == EarlyStateArchive.maximumProfiles { + #expect(workspace.createProfile(name: "One extra") == nil) + #expect(workspace.profiles.count == count) + } + } + + @Test func aValidArchiveCannotMakeTheDestinationExceedTheProfileLimit() throws { + let source = try workspace(withProfiles: EarlyStateArchive.maximumProfiles) + let archive = try EarlyStateArchive.decode(EarlyStateArchive(workspace: source, settings: nil).encoded()) + let current = BrowserWorkspace() + #expect(throws: EarlyStateArchive.Problem.tooManyProfiles) { try archive.merged(into: current, mode: .addProfiles) } + let replacement = try archive.merged(into: current, mode: .replaceMatching) + let bytes = try EarlyStateArchive(workspace: replacement.workspace, settings: nil).encoded() + #expect(try EarlyStateArchive.decode(bytes).workspace.profiles.count == EarlyStateArchive.maximumProfiles) + #expect(replacement.replaced == [current.defaultProfileID]) + } + + @Test func anOversizedLegacySessionCanBeRecoveredAndLeavesOlderBackupsIntact() async throws { + let files = FileManager.default + let directory = files.temporaryDirectory.appendingPathComponent("EarlyLegacySession-\(UUID())") + let live = directory.appendingPathComponent("Live"), recovered = directory.appendingPathComponent("Recovered") + let backups = directory.appendingPathComponent("Backups") + defer { try? files.removeItem(at: directory) } + let supported = try workspace(withProfiles: EarlyStateArchive.maximumProfiles) + var legacy = supported + let extra = BrowserSession() + legacy.profiles.append(BrowserProfile(id: extra.profileID, name: "Legacy profile")) + legacy.sessions.append(extra) + do { + let repository = SessionRepository(fileURL: live.appendingPathComponent("session.sqlite")) + try await repository.saveWorkspace(legacy, revision: 1) + } + try files.copyItem(at: live, to: recovered) + let repository = SessionRepository(fileURL: recovered.appendingPathComponent("session.sqlite")) + #expect(try await repository.loadWorkspace() == legacy) + #expect(throws: EarlyStateArchive.Problem.tooManyProfiles) { try EarlyStateArchive.decode(unvalidatedBytes(of: legacy)) } + + var saved: [URL] = [] + for _ in 0..<6 { + saved.append(try EarlyStateArchive.backup(workspace: supported, settings: nil, in: backups, retaining: 6)) + } + #expect(throws: EarlyStateArchive.Problem.tooManyProfiles) { + try EarlyStateArchive.backup(workspace: legacy, settings: nil, in: backups, retaining: 5) + } + #expect(Set(try files.contentsOfDirectory(atPath: backups.path)) == Set(saved.map(\.lastPathComponent))) + #expect(try EarlyStateArchive.read(from: #require(saved.last), using: input).workspace == supported) + } + + @Test func tabCapacityCountsEveryWindowAndRejectsGrowthAcrossTheLimit() throws { + var session = BrowserSession() + let limit = EarlyStateArchive.maximumTabs + func newTab() -> BrowserTab { + BrowserTab(spaceID: session.activeSpaceID, profileID: session.profileID, title: "Page", currentURL: docs) + } + session.tabs = (0..<(limit / 2)).map { _ in newTab() } + let siblingTabs = (session.tabs.count..