Skip to content

armgit / cra

Public Imported from GitHub
0

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.

Test architecture: clock, faults, policies, scenarios, gates (#45) (#67)

Victor Kildahl0467d41062db
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 59bd8f1..bf9a808 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -14,12 +14,36 @@ jobs:
name: Tests
# No Chromium download: Packages/CraCore and the harnesses compile only the files they test.
runs-on: macos-26
+ permissions:
+ contents: read
+ pull-requests: write
steps:
- uses: actions/checkout@v7
+ with:
+ fetch-depth: 0
- - name: CraCore and harnesses
+ - name: CraCore, harnesses and lint
run: scripts/test.sh
+ # Changed lines under test >= 70 %, CraCore >= 85 % (docs/testing.md).
+ - name: Coverage
+ if: github.event_name == 'pull_request' || github.event.before != '0000000000000000000000000000000000000000'
+ run: |
+ set -o pipefail
+ scripts/coverage.py --base "${{ github.event.pull_request.base.sha || github.event.before }}" | tee coverage.md
+
+ # Fork pull requests get a read-only token: the job summary has the same table.
+ - name: Coverage comment
+ if: always() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
+ continue-on-error: true
+ env:
+ GH_TOKEN: ${{ github.token }}
+ PR: ${{ github.event.pull_request.number }}
+ run: |
+ [ -s coverage.md ] || exit 0
+ { echo "### Coverage"; echo; cat coverage.md; } > comment.md
+ gh pr comment "$PR" --body-file comment.md --edit-last 2>/dev/null || gh pr comment "$PR" --body-file comment.md
+
build:
name: Build Cra.app
# Same runner as release.yml, so CI builds what ships.
@@ -51,3 +75,18 @@ jobs:
continue-on-error: true
timeout-minutes: 5
run: Tests/smoke-launch.sh build/Cra.app
+
+ # One short journey on every pull request (thirty tabs put to sleep); the full set and the
+ # component snapshots run nightly (nightly.yml). Not blocking until steady on these runners.
+ - name: Scenario
+ continue-on-error: true
+ timeout-minutes: 5
+ run: scripts/scenario.sh sleep-tabs
+
+ - name: Keep scenario logs
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: scenario-logs
+ path: build/scenarios
+ if-no-files-found: ignore
diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml
new file mode 100644
index 0000000..24087db
--- /dev/null
+++ b/.github/workflows/nightly.yml
@@ -0,0 +1,107 @@
+name: Nightly
+
+# The slow test layers (docs/testing.md): every scenario on both sidebar backdrop paths
+# (the private CABackdropLayer one and NSVisualEffectView), fullscreen included; the harnesses
+# under AddressSanitizer, ThreadSanitizer and UBSan; the parser fuzzer; and on Mondays
+# mutation testing. Also by hand: Actions ▸ Nightly ▸ Run workflow.
+on:
+ schedule:
+ - cron: "17 2 * * *"
+ - cron: "41 3 * * 1"
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ scenarios:
+ name: Scenarios (backdrop=${{ matrix.backdrop }})
+ runs-on: macos-26
+ timeout-minutes: 60
+ strategy:
+ fail-fast: false
+ matrix:
+ backdrop: [layer, material]
+ steps:
+ - uses: actions/checkout@v7
+
+ - name: Read pinned CEF version
+ id: cef
+ run: echo "version=$(sed -n 's/^CEF_VERSION="${CEF_VERSION:-\(.*\)}"$/\1/p' scripts/fetch-cef.sh)" >> "$GITHUB_OUTPUT"
+
+ - name: Cache CEF
+ uses: actions/cache@v6
+ with:
+ path: vendor/cef
+ key: cef-${{ runner.arch }}-${{ steps.cef.outputs.version }}-${{ hashFiles('scripts/fetch-cef.sh') }}
+
+ - name: Build (debug, ad-hoc signed)
+ run: scripts/build.sh debug
+
+ - name: Scenarios
+ env:
+ CRA_FLAGS: backdrop=${{ matrix.backdrop }}
+ CRA_SCENARIO_SCREEN: "1"
+ run: |
+ {
+ echo "## Scenarios, backdrop=${{ matrix.backdrop }}"
+ echo
+ echo "| Scenario | Result | Longest stall / over 50 ms | Memory | Problems |"
+ echo "|---|---|---|---|---|"
+ } >> "$GITHUB_STEP_SUMMARY"
+ scripts/scenario.sh all
+
+ - name: Keep logs
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: scenarios-${{ matrix.backdrop }}
+ path: build/scenarios
+ if-no-files-found: ignore
+
+ sanitizers:
+ name: Harnesses under ${{ matrix.sanitizer }} sanitizer
+ runs-on: macos-26
+ timeout-minutes: 30
+ strategy:
+ fail-fast: false
+ matrix:
+ sanitizer: [address, thread, undefined]
+ steps:
+ - uses: actions/checkout@v7
+ - name: Harnesses
+ env:
+ CRA_TEST_SWIFTC_FLAGS: -sanitize=${{ matrix.sanitizer }}
+ run: |
+ for t in scripts/test-*.sh Tests/test-*.sh; do
+ case "$t" in scripts/test-update.sh|scripts/test.sh) continue ;; esac
+ echo "== $t"; bash "$t"
+ done
+
+ fuzz:
+ name: Parser fuzzing
+ runs-on: macos-26
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@v7
+ - name: 400 000 mutated inputs under AddressSanitizer
+ env:
+ CRA_FUZZ_ITERATIONS: "400000"
+ CRA_FUZZ_SEED: ${{ github.run_id }}
+ run: scripts/fuzz.sh
+ - name: Keep the crashing input
+ if: failure()
+ uses: actions/upload-artifact@v7
+ with:
+ name: fuzz-crash
+ path: build/fuzz
+
+ mutation:
+ name: Mutation testing
+ if: github.event_name == 'workflow_dispatch' || github.event.schedule == '41 3 * * 1'
+ runs-on: macos-26
+ timeout-minutes: 90
+ steps:
+ - uses: actions/checkout@v7
+ - name: Mutants of the pure code (70 % must be caught)
+ run: scripts/mutate.py
diff --git a/Packages/CraCore/Tests/CraCoreTests/ArcThemeImportTests.swift b/Packages/CraCore/Tests/CraCoreTests/ArcThemeImportTests.swift
index 21de28f..250d520 100644
--- a/Packages/CraCore/Tests/CraCoreTests/ArcThemeImportTests.swift
+++ b/Packages/CraCore/Tests/CraCoreTests/ArcThemeImportTests.swift
@@ -59,6 +59,63 @@ struct ArcThemeImportTests {
@Test func spaceWithoutAThemeImportsNone() {
#expect(Self.theme("noWindowTheme") == nil)
}
+
+ /// A fixture space with its background variant (single, or the appearance-based one read)
+ /// changed: the same file, one field different.
+ static func theme(_ name: String, changing change: (inout [String: Any]) -> Void) -> SpaceTheme? {
+ var space = spaces[name]!
+ var info = space["customInfo"] as! [String: Any]
+ var wt = info["windowTheme"] as! [String: Any]
+ var bg = wt["background"] as! [String: Any]
+ if var single = bg["single"] as? [String: Any] {
+ var v = single["_0"] as! [String: Any]
+ change(&v)
+ single["_0"] = v
+ bg["single"] = single
+ } else {
+ var ab = bg["appearanceBased"] as! [String: Any]
+ let key = ab["dark"] != nil ? "dark" : "light"
+ var v = ab[key] as! [String: Any]
+ change(&v)
+ ab[key] = v
+ bg["appearanceBased"] = ab
+ }
+ wt["background"] = bg
+ info["windowTheme"] = wt
+ space["customInfo"] = info
+ return ArcThemeImport.theme(from: space)
+ }
+
+ static func gradient(_ v: inout [String: Any], _ change: (inout [String: Any]) -> Void) {
+ var style = v["style"] as! [String: Any], color = style["color"] as! [String: Any], c0 = color["_0"] as! [String: Any]
+ var bg = c0["blendedGradient"] as! [String: Any], g = bg["_0"] as! [String: Any]
+ change(&g)
+ bg["_0"] = g; c0["blendedGradient"] = bg; color["_0"] = c0; style["color"] = color; v["style"] = style
+ }
+
+ /// Arc lets a gradient have one base colour; both stops then come from it.
+ @Test(arguments: ["gradientVibrantLight", "gradientAppearanceBasedDark"])
+ func oneBaseColourGradient(name: String) throws {
+ let full = try #require(Self.theme(name))
+ let theme = try #require(Self.theme(name) { v in
+ Self.gradient(&v) { g in g["baseColors"] = [(g["baseColors"] as! [[String: Any]])[0]] }
+ })
+ #expect(theme.colors.count == 2 && theme.accent == full.accent, "the first base colour stays the accent")
+ }
+
+ /// Only a vibrant light theme gets the over-the-desktop fit; the same gradient opaque keeps its stops.
+ @Test func opaqueLightGradientSkipsTheVibrantFit() throws {
+ let vibrant = try #require(Self.theme("gradientVibrantLight"))
+ let opaque = try #require(Self.theme("gradientVibrantLight") { $0["isVibrant"] = false })
+ #expect(!opaque.vibrant && opaque.colors != vibrant.colors && opaque.intensity == vibrant.intensity)
+ }
+
+ /// Only an opaque dark theme is darkened over Arc's #2B2632; a vibrant dark one keeps its stops.
+ @Test func vibrantDarkGradientIsNotDarkened() throws {
+ let opaque = try #require(Self.theme("gradientAppearanceBasedDark"))
+ let vibrant = try #require(Self.theme("gradientAppearanceBasedDark") { $0["isVibrant"] = true })
+ #expect(vibrant.vibrant && vibrant.colors != opaque.colors && vibrant.intensity != 1)
+ }
}
struct SpaceThemeTests {
@@ -74,6 +131,12 @@ struct SpaceThemeTests {
#expect(try JSONDecoder().decode(SpaceTheme.self, from: JSONEncoder().encode(theme)) == theme)
}
+ /// A theme that says its appearance keeps it, whatever its colours.
+ @Test func explicitAppearanceWinsOverTheColours() {
+ #expect(SpaceTheme(colors: ["#FFFFFF", "#FFFFFF"], intensity: 1, noise: 0, appearance: "dark").isDark)
+ #expect(!SpaceTheme(colors: ["#000000", "#000000"], intensity: 1, noise: 0, appearance: "light").isDark)
+ }
+
@Test(arguments: [("#000000", true), ("#FFFFFF", false), ("#2861B3", true), ("#F8D558", false)])
func autoAppearanceFollowsTheFirstColour(hex: String, dark: Bool) {
#expect(SpaceTheme(colors: [hex, hex], intensity: 1, noise: 0, appearance: "auto").isDark == dark)
diff --git a/Sources/Cra/App/AppComposition.swift b/Sources/Cra/App/AppComposition.swift
new file mode 100644
index 0000000..1db8240
--- /dev/null
+++ b/Sources/Cra/App/AppComposition.swift
@@ -0,0 +1,36 @@
+import Foundation
+
+/// What a running Cra is made of, built once: the clock, the feature flags and the store on
+/// the data folder's files (CRA_DATA_DIR for a test instance). AppDelegate builds it at launch;
+/// a test host builds the same graph with a manual clock (Tests/StoreTests.swift), so timed
+/// work is tried on the code that ships rather than on a copy of it.
+@MainActor
+final class AppComposition {
+ let clock: Scheduler
+ let flags: FeatureFlags
+ let store: SidebarStore
+ private var periodic: [ScheduledWork] = []
+
+ init(clock: Scheduler? = nil, flags: FeatureFlags = .current) {
+ self.clock = clock ?? LiveScheduler.shared
+ self.flags = flags
+ store = SidebarStore(clock: self.clock)
+ }
+
+ /// Arc archives on a 30-minute pass; tab sleeping looks every minute. `sleepTabs` reaches
+ /// the windows' browser managers, which the composition does not own.
+ static let autoArchiveInterval: TimeInterval = 1800
+ static let tabSleepInterval: TimeInterval = 60
+
+ func startPeriodicWork(sleepTabs: @escaping @MainActor () -> Void) {
+ periodic.forEach { $0.cancel() }
+ store.runAutoArchive()
+ periodic = [
+ clock.every(Self.autoArchiveInterval) { [weak self] in self?.store.runAutoArchive() },
+ clock.every(Self.tabSleepInterval) { [weak self] in
+ guard let self, self.store.settings.tabSleepEnabled else { return }
+ sleepTabs()
+ },
+ ]
+ }
+}
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index a589a01..48a59e6 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -4,7 +4,9 @@ import SwiftUI
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
- let store = SidebarStore()
+ /// The store, clock and flags; built the same way by the test hosts.
+ let composition = AppComposition()
+ var store: SidebarStore { composition.store }
let bindings = KeyBindingRegistry()
let favicons = FaviconCache()
lazy var engine = SuggestionEngine(store: store, bindings: bindings)
@@ -17,8 +19,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
}
private var bootstrapped = false
private var pendingURLs: [String] = []
- private var autoArchiveTimer: Timer?
- private var tabSleepTimer: Timer?
private var settingsWindow: NSWindow?
private var settingsController: SettingsWindowController?
private var isRelaunching = false
@@ -65,13 +65,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
}
installKeyFallbackMonitor()
installCommandFileWatcher()
- store.runAutoArchive()
- autoArchiveTimer = Timer.scheduledTimer(withTimeInterval: 1800, repeats: true) { [weak self] _ in
- Task { @MainActor in self?.store.runAutoArchive() }
- }
- tabSleepTimer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
- Task { @MainActor in self?.sleepIdleTabs() }
- }
+ composition.startPeriodicWork { [weak self] in self?.sleepIdleTabs() }
+ logSidebarProblems()
LiveFolderManager.shared.start(store: store)
// A restart into an update while the user was away leaves the front app alone.
if HitchMonitor.background {
@@ -165,8 +160,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
observeHttpsOnly()
}
+ /// A sidebar whose links disagree (SidebarIntegrity) says so in the log, one fault a problem.
+ private func logSidebarProblems() {
+ let problems = store.integrityProblems()
+ for p in problems.prefix(20) { CraLog.fault("sidebar: \(p)") }
+ if problems.count > 20 { CraLog.fault("sidebar: \(problems.count - 20) more problems") }
+ }
+
private func sleepIdleTabs() {
- guard store.settings.tabSleepEnabled else { return }
for w in mainWindows { w.browsers.sleepIdleTabs(hiddenLongerThan: store.settings.tabSleep.seconds) }
}
@@ -487,6 +488,27 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
return
}
if let st = dict["status"] { main.browserManager(statusMessage: st); return }
+ // Scenario hooks (scripts/scenario.sh): what a journey needs without a pointer.
+ if dict["checkStore"] != nil { logSidebarProblems(); return }
+ if let js = dict["pageJS"] { main.currentBrowser?.executeJavaScript(js); return }
+ if let path = dict["installExtension"] {
+ do { try ExtensionStore.shared.add(folder: URL(fileURLWithPath: path, isDirectory: true)) } catch {
+ CraLog.note("scenario: extension not installed: \(error.localizedDescription)")
+ }
+ return
+ }
+ if let id = dict["removeExtension"] {
+ if let e = ExtensionStore.shared.entries.first(where: { $0.extensionID == id }) { ExtensionStore.shared.remove(e) }
+ return
+ }
+ if let v = dict["fullscreen"], let w = main.window, (v == "1") != w.styleMask.contains(.fullScreen) { w.toggleFullScreen(nil); return }
+ if let spec = dict["snapshot"], let out = dict["out"] { ViewSnapshot.write(spec, in: main.window, to: out); return }
+ if let size = dict["windowSize"]?.split(separator: "x").compactMap({ Double($0) }), size.count == 2, let w = main.window {
+ w.setFrame(NSRect(x: w.frame.minX, y: w.frame.maxY - size[1], width: size[0], height: size[1]), display: true)
+ return
+ }
+ if dict["relaunch"] != nil { relaunch(); return }
+ if dict["quit"] != nil { NSApp.terminate(nil); return }
if let t = dict["selectTab"].flatMap(UUID.init(uuidString:)) { store.selectTab(t, window: main.windowID); return }
// One tab-sleeping pass with a short threshold (seconds), so it can be tried without waiting.
if let s = dict["sleepTabs"].flatMap(Double.init) {
@@ -620,24 +642,24 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
/// is handled like a cra:// URL (a second instance run with CRA_DATA_DIR
/// cannot receive cra:// URLs, which LaunchServices routes to the installed app).
private var commandFileOffset: UInt64 = 0
- private var commandFileTimer: Timer?
+ private var commandFilePoll: ScheduledWork?
private func installCommandFileWatcher() {
guard let path = ProcessInfo.processInfo.environment["CRA_COMMAND_FILE"], !path.isEmpty else { return }
FileManager.default.createFile(atPath: path, contents: nil)
commandFileOffset = (try? FileManager.default.attributesOfItem(atPath: path)[.size] as? UInt64) ?? 0
- commandFileTimer = Timer.scheduledTimer(withTimeInterval: 0.15, repeats: true) { [weak self] _ in
- Task { @MainActor in
- guard let self, let h = FileHandle(forReadingAtPath: path) else { return }
- defer { try? h.close() }
- let size = (try? h.seekToEnd()) ?? 0
- guard size > self.commandFileOffset else { return }
- try? h.seek(toOffset: self.commandFileOffset)
- let data = h.readDataToEndOfFile()
- self.commandFileOffset = size
- for line in String(decoding: data, as: UTF8.self).split(separator: "\n") {
- HitchMonitor.mark(String(line))
- if let u = URL(string: line.trimmingCharacters(in: .whitespaces)) { self.handleInternalURL(u) }
- }
+ // A script writes only after this line: the file above starts empty.
+ CraLog.note("pid \(getpid()) reads commands from CRA_COMMAND_FILE")
+ commandFilePoll = composition.clock.every(0.15) { [weak self] in
+ guard let self, let h = FileHandle(forReadingAtPath: path) else { return }
+ defer { try? h.close() }
+ let size = (try? h.seekToEnd()) ?? 0
+ guard size > self.commandFileOffset else { return }
+ try? h.seek(toOffset: self.commandFileOffset)
+ let data = h.readDataToEndOfFile()
+ self.commandFileOffset = size
+ for line in String(decoding: data, as: UTF8.self).split(separator: "\n") {
+ HitchMonitor.mark(String(line))
+ if let u = URL(string: line.trimmingCharacters(in: .whitespaces)) { self.handleInternalURL(u) }
}
}
}
@@ -772,8 +794,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
case "viewSource": main.currentBrowser?.viewSource()
case "devTools", "jsConsole":
// Toggle, like Chrome: ⌥⌘I closes the dock when it is already open.
- if let b = main.currentBrowser { b.hasDevTools ? b.closeDevTools() : b.showDevTools() }
- case "inspectElement": main.currentBrowser?.showDevTools()
+ main.browsers.toggleDevTools()
+ case "inspectElement": main.browsers.showDevTools()
// Arc's Library is a mode of the window's sidebar; ⇧⌘J opens it on Downloads.
case "openLibrary": main.toggleLibrary()
case "viewArchive": main.showLibrary(.archive)
diff --git a/Sources/Cra/App/FeatureFlags.swift b/Sources/Cra/App/FeatureFlags.swift
new file mode 100644
index 0000000..d8896c1
--- /dev/null
+++ b/Sources/Cra/App/FeatureFlags.swift
@@ -0,0 +1,28 @@
+import Foundation
+
+/// Switches for the paths that rest on private or fragile API, so a scenario can run each
+/// one and a new macOS that breaks the private path fails a gate instead of shipping.
+/// CRA_FLAGS="backdrop=material" sets them for a test instance; the log names the choice once.
+struct FeatureFlags: Equatable {
+ enum Backdrop: String { case layer, material }
+ /// `layer`: the sidebar's behind-window blur is a CABackdropLayer with Core Animation's
+ /// private gaussian CAFilter (ShellView), calibrated against Arc; it falls back to
+ /// `material` when the runtime lacks those classes. `material`: NSVisualEffectView only.
+ var backdrop: Backdrop = .layer
+
+ init(backdrop: Backdrop = .layer) { self.backdrop = backdrop }
+
+ /// "backdrop=material&…"; unknown keys and values keep the defaults.
+ init(parsing spec: String) {
+ self.init()
+ for pair in spec.split(separator: "&") {
+ let kv = pair.split(separator: "=", maxSplits: 1).map(String.init)
+ guard kv.count == 2 else { continue }
+ if kv[0] == "backdrop", let v = Backdrop(rawValue: kv[1]) { backdrop = v }
+ }
+ }
+
+ static let current = FeatureFlags(parsing: ProcessInfo.processInfo.environment["CRA_FLAGS"] ?? "")
+
+ var summary: String { "backdrop=\(backdrop.rawValue)" }
+}
diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swift
index a0b7f02..1586611 100644
--- a/Sources/Cra/Services/BrowserManager.swift
+++ b/Sources/Cra/Services/BrowserManager.swift
@@ -19,13 +19,15 @@ final class TabRuntime {
var snapshot: NSImage?
var snapshotWork: DispatchWorkItem?
/// When the page last went off screen (nil while shown); tab sleeping counts from here.
- var hiddenAt: Date? = Date()
+ var hiddenAt: Date?
/// Invalidates a pending sleep probe even when navigation returns to the same URL.
var navigationRevision: UInt = 0
/// A page that refused to sleep isn't asked again before this (nil: ask on the next pass).
var sleepProbeAfter: Date?
/// Why the page last refused to sleep ("" when it didn't), so the log says it once.
var sleepRefusal: String?
+ /// Whether this page's DevTools are open, closing or asked for (DevToolsToggle).
+ var devTools = DevToolsToggle()
/// Chrome-style hosting: the page's own window (nil until created, or for Alloy).
var hostWindow: NSWindow? { browser.hostWindow }
init(tabID: UUID, browser: CraBrowser) {
@@ -83,10 +85,14 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
/// CEF's client holds its owner weakly; keep retired browsers alive until teardown finishes.
private var closingBrowsers: [ObjectIdentifier: CraBrowser] = [:]
- init(store: SidebarStore, favicons: FaviconCache, container: NSView) {
+ /// Tab sleeping's clock: a test advances it instead of waiting out the idle threshold.
+ let clock: Scheduler
+
+ init(store: SidebarStore, favicons: FaviconCache, container: NSView, clock: Scheduler? = nil) {
self.store = store
self.favicons = favicons
self.container = container
+ self.clock = clock ?? LiveScheduler.shared
}
func runtime(for tabID: UUID) -> TabRuntime? { runtimes[tabID] }
@@ -135,6 +141,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
private func register(browser: CraBrowser, tabID: UUID) -> TabRuntime {
browser.userInfo = tabID.uuidString
let rt = TabRuntime(tabID: tabID, browser: browser)
+ rt.hiddenAt = clock.now
if let t = store.item(tabID)?.tab, t.muted { browser.setAudioMuted(true) }
add(rt)
return rt
@@ -191,7 +198,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
let newSet = Set(tabIDs)
for previous in visibleTabIDs where !newSet.contains(previous) {
leaveTab(previous)
- runtimes[previous]?.hiddenAt = Date()
+ runtimes[previous]?.hiddenAt = clock.now
}
let wasVisible = Set(visibleTabIDs)
var shown: [UUID] = []
@@ -333,7 +340,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
/// user typed or asking before they close (their own onbeforeunload) stay awake, and are
/// asked again only after `refusalBackoff`. The log says once why a page stays awake.
func sleepIdleTabs(hiddenLongerThan seconds: TimeInterval) {
- let now = Date()
+ let now = clock.now
let cutoff = now.addingTimeInterval(-seconds)
for (id, rt) in runtimes {
let b = rt.browser
@@ -353,7 +360,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
let refusal = Self.sleepRefusal(result)
guard refusal.isEmpty else { return self.keepAwake(rt, url, refusal) }
if !rt.browser.isIncognito {
- CraLog.note("tab sleep unloads \(CraLog.host(url)) (hidden \(Int(Date().timeIntervalSince(rt.hiddenAt ?? Date()) / 60)) min)")
+ CraLog.note("tab sleep unloads \(CraLog.host(url)) (hidden \(Int(self.clock.now.timeIntervalSince(rt.hiddenAt ?? self.clock.now) / 60)) min)")
}
self.unload(id)
}
@@ -369,7 +376,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
/// Asked again after the back-off; the log names the site once per reason (never an incognito one).
private func keepAwake(_ rt: TabRuntime, _ url: String, _ refusal: String) {
- rt.sleepProbeAfter = Date().addingTimeInterval(Self.refusalBackoff)
+ rt.sleepProbeAfter = clock.now.addingTimeInterval(Self.refusalBackoff)
if rt.sleepRefusal != refusal, !rt.browser.isIncognito { CraLog.note("tab sleep keeps \(CraLog.host(url)) awake: \(refusal)") }
rt.sleepRefusal = refusal
}
@@ -720,6 +727,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
func browser(_ browser: CraBrowser, didCreateDevToolsView view: NSView) {
guard let id = tabID(of: browser) else { return }
devToolsViews[id] = view
+ runtimes[id]?.devTools.didOpen()
delegate?.browserManagerDevToolsChanged()
}
@@ -729,6 +737,27 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
devToolsPlaceholders[id] = nil
devToolsDockedState[id] = nil
delegate?.browserManagerDevToolsChanged()
+ if let rt = runtimes[id] { perform(rt.devTools.didClose(), on: rt) }
+ }
+
+ /// ⌥⌘I on the focused page: open its DevTools, or close them (DevToolsToggle).
+ func toggleDevTools() {
+ guard let rt = visibleRuntime else { return }
+ perform(rt.devTools.toggle(), on: rt)
+ }
+
+ /// Inspect Element: DevTools open on the focused page, whatever they were doing.
+ func showDevTools() {
+ guard let rt = visibleRuntime else { return }
+ perform(rt.devTools.show(), on: rt)
+ }
+
+ private func perform(_ effect: DevToolsToggle.Effect, on rt: TabRuntime) {
+ switch effect {
+ case .show: rt.browser.showDevTools()
+ case .close: rt.browser.closeDevTools()
+ case .none: break
+ }
}
/// Chrome's docked frontend reported where the page goes: `bounds` are points with a
diff --git a/Sources/Cra/Services/CraLog.swift b/Sources/Cra/Services/CraLog.swift
new file mode 100644
index 0000000..34ff41c
--- /dev/null
+++ b/Sources/Cra/Services/CraLog.swift
@@ -0,0 +1,82 @@
+import Foundation
+
+/// Cra's own log, `cra.log` next to Chromium's: what Cra did with each page (opened, shown,
+/// loaded, closed) and what the page looked like a moment after it was shown, so a report of
+/// a tab that "stays white" can be traced without a debugger. Lines name sites by host only,
+/// never the full address: the log is meant to be sent (Help ▸ Export Diagnostics…).
+enum CraLog {
+ private static let queue = DispatchQueue(label: "dk.kildahl.cra.log", qos: .utility)
+ nonisolated(unsafe) private static var handle: FileHandle?
+ nonisolated(unsafe) private static var written = 0
+ /// A runaway loop must not fill the disk; a session's log is a few hundred kB.
+ private static let limit = 8 << 20
+
+ static var file: URL { AppPaths.file("cra.log") }
+ static var previousFile: URL { AppPaths.file("cra.previous.log") }
+ static var chromiumPreviousFile: URL { AppPaths.file("chromium.previous.log") }
+
+ /// Before Chromium starts. Only the Cra that owns the data folder rotates: a second launch
+ /// that hands its URLs to the running one and quits would move that one's logs away.
+ static func startSession(owner: Bool) {
+ let fm = FileManager.default
+ if owner {
+ for (current, previous) in [(file, previousFile), (AppPaths.log, chromiumPreviousFile)] where fm.fileExists(atPath: current.path) {
+ try? fm.removeItem(at: previous)
+ try? fm.moveItem(at: current, to: previous)
+ }
+ }
+ // Above 10: Chromium's DevTools pipe needs descriptors 3 and 4 free (CraCDPPipeSetUp),
+ // and this file is opened before Chromium starts.
+ let fd = open(file.path, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0o644)
+ if fd >= 0 {
+ let high = fcntl(fd, F_DUPFD_CLOEXEC, 10)
+ close(fd)
+ if high >= 0 { handle = FileHandle(fileDescriptor: high, closeOnDealloc: true) }
+ }
+ let info = Bundle.main.infoDictionary
+ note("Cra \(info?["CFBundleShortVersionString"] as? String ?? "?") (\(info?["CFBundleVersion"] as? String ?? "?")) starts, pid \(getpid())\(owner ? "" : ", another Cra owns the data folder")")
+ }
+
+ /// Faults this session (the tests read it; persistence reports from its own queue).
+ nonisolated(unsafe) private(set) static var faultCount = 0
+ private static let faultLock = NSLock()
+
+ /// Something Cra assumes never happens just did: a state the code cannot be in, a write
+ /// that failed. Logged as "fault: …" rather than failing silently, so a report shows it
+ /// and a scenario run (scripts/scenario.sh) fails on any. With CRA_FAULT_TRAP=1 a debug
+ /// build stops there instead.
+ static func fault(_ message: String, file: StaticString = #fileID, line: UInt = #line) {
+ faultLock.lock()
+ faultCount += 1
+ faultLock.unlock()
+ note("fault: \(message) (\(file):\(line))")
+ #if DEBUG
+ if ProcessInfo.processInfo.environment["CRA_FAULT_TRAP"] == "1" { raise(SIGTRAP) }
+ #endif
+ }
+
+ static func note(_ message: String) {
+ NSLog("Cra: %@", message)
+ let line = "\(timestamp.string(from: Date())) \(message)\n"
+ queue.async {
+ guard let handle, written < limit, let data = line.data(using: .utf8) else { return }
+ written += data.count
+ try? handle.write(contentsOf: data)
+ }
+ }
+
+ /// Waits for lines still being written (before the log is copied).
+ static func flush() { queue.sync {} }
+
+ private static let timestamp: DateFormatter = {
+ let f = DateFormatter()
+ f.locale = Locale(identifier: "en_US_POSIX")
+ f.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
+ return f
+ }()
+
+ /// Only the host: logs get shared in bug reports.
+ static func host(_ url: String) -> String {
+ URL(string: url).flatMap { $0.host ?? $0.scheme.map { "\($0):" } } ?? "(no page)"
+ }
+}
diff --git a/Sources/Cra/Services/DevToolsToggle.swift b/Sources/Cra/Services/DevToolsToggle.swift
new file mode 100644
index 0000000..8824b93
--- /dev/null
+++ b/Sources/Cra/Services/DevToolsToggle.swift
@@ -0,0 +1,55 @@
+import Foundation
+
+/// ⌥⌘I on a page, as in Chrome: open DevTools, or close them when open. CEF's HasDevTools()
+/// stays true until the DevTools frontend has gone, so deciding from it made a second press
+/// while they closed close them again (nothing happened). This follows the page's DevTools
+/// from Cra's requests and CEF's callbacks instead, and remembers a press made mid-close.
+struct DevToolsToggle: Equatable {
+ enum State: Equatable { case closed, opening, open, closing(reopen: Bool) }
+ enum Effect: Equatable { case show, close, none }
+
+ private(set) var state = State.closed
+
+ /// The shortcut, the developer bar's button, the menu item.
+ mutating func toggle() -> Effect {
+ switch state {
+ case .closed:
+ state = .opening
+ return .show
+ case .opening, .open:
+ state = .closing(reopen: false)
+ return .close
+ case .closing(let reopen):
+ state = .closing(reopen: !reopen)
+ return .none
+ }
+ }
+
+ /// Inspect Element: DevTools must end up open (and CEF moves them to the element).
+ mutating func show() -> Effect {
+ switch state {
+ case .closed, .opening, .open:
+ if state == .closed { state = .opening }
+ return .show
+ case .closing:
+ state = .closing(reopen: true)
+ return .none
+ }
+ }
+
+ /// CEF made the DevTools view, also for DevTools opened from Chromium's own menu.
+ mutating func didOpen() {
+ if case .closing = state { return }
+ state = .open
+ }
+
+ /// CEF reports them gone; a press made while they closed opens them again now.
+ mutating func didClose() -> Effect {
+ if case .closing(reopen: true) = state {
+ state = .opening
+ return .show
+ }
+ state = .closed
+ return .none
+ }
+}
diff --git a/Sources/Cra/Services/Diagnostics.swift b/Sources/Cra/Services/Diagnostics.swift
index 3eabb74..b1ee13f 100644
--- a/Sources/Cra/Services/Diagnostics.swift
+++ b/Sources/Cra/Services/Diagnostics.swift
@@ -2,133 +2,6 @@ import AppKit
import CraCEF
import UniformTypeIdentifiers
-/// Cra's own log, `cra.log` next to Chromium's: what Cra did with each page (opened, shown,
-/// loaded, closed) and what the page looked like a moment after it was shown, so a report of
-/// a tab that "stays white" can be traced without a debugger. Lines name sites by host only,
-/// never the full address: the log is meant to be sent (Help ▸ Export Diagnostics…).
-enum CraLog {
- private static let queue = DispatchQueue(label: "dk.kildahl.cra.log", qos: .utility)
- nonisolated(unsafe) private static var handle: FileHandle?
- nonisolated(unsafe) private static var written = 0
- /// A runaway loop must not fill the disk; a session's log is a few hundred kB.
- private static let limit = 8 << 20
-
- static var file: URL { AppPaths.file("cra.log") }
- static var previousFile: URL { AppPaths.file("cra.previous.log") }
- static var chromiumPreviousFile: URL { AppPaths.file("chromium.previous.log") }
-
- /// Before Chromium starts. Only the Cra that owns the data folder rotates: a second launch
- /// that hands its URLs to the running one and quits would move that one's logs away.
- static func startSession(owner: Bool) {
- let fm = FileManager.default
- if owner {
- for (current, previous) in [(file, previousFile), (AppPaths.log, chromiumPreviousFile)] where fm.fileExists(atPath: current.path) {
- try? fm.removeItem(at: previous)
- try? fm.moveItem(at: current, to: previous)
- }
- }
- // Above 10: Chromium's DevTools pipe needs descriptors 3 and 4 free (CraCDPPipeSetUp),
- // and this file is opened before Chromium starts.
- let fd = open(file.path, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0o644)
- if fd >= 0 {
- let high = fcntl(fd, F_DUPFD_CLOEXEC, 10)
- close(fd)
- if high >= 0 { handle = FileHandle(fileDescriptor: high, closeOnDealloc: true) }
- }
- let info = Bundle.main.infoDictionary
- note("Cra \(info?["CFBundleShortVersionString"] as? String ?? "?") (\(info?["CFBundleVersion"] as? String ?? "?")) starts, pid \(getpid())\(owner ? "" : ", another Cra owns the data folder")")
- }
-
- static func note(_ message: String) {
- NSLog("Cra: %@", message)
- let line = "\(timestamp.string(from: Date())) \(message)\n"
- queue.async {
- guard let handle, written < limit, let data = line.data(using: .utf8) else { return }
- written += data.count
- try? handle.write(contentsOf: data)
- }
- }
-
- /// Waits for lines still being written (before the log is copied).
- static func flush() { queue.sync {} }
-
- private static let timestamp: DateFormatter = {
- let f = DateFormatter()
- f.locale = Locale(identifier: "en_US_POSIX")
- f.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
- return f
- }()
-
- /// Only the host: logs get shared in bug reports.
- static func host(_ url: String) -> String {
- URL(string: url).flatMap { $0.host ?? $0.scheme.map { "\($0):" } } ?? "(no page)"
- }
-}
-
-/// What a page holds, asked from the page itself: a blank tab tells apart a navigation that
-/// never committed (about:blank), a page Chromium thinks is hidden, one that has content but
-/// never painted it, and one that is simply empty.
-@MainActor
-enum PageProbe {
- private static let script = """
- JSON.stringify({blank: location.href === 'about:blank', ready: document.readyState, visibility: document.visibilityState,
- viewport: innerWidth + 'x' + innerHeight + '@' + devicePixelRatio,
- scrollHeight: document.documentElement ? document.documentElement.scrollHeight : 0,
- elements: document.getElementsByTagName('*').length,
- text: document.body ? document.body.textContent.length : -1,
- painted: performance.getEntriesByName('first-contentful-paint').length > 0})
- """
-
- /// One line ("ready=complete visibility=visible …"), or why there is none.
- static func run(_ browser: CraBrowser, completion: @escaping (String) -> Void) {
- guard browser.isCreated, !browser.isClosed else { completion("no browser yet"); return }
- let body = try? JSONSerialization.data(withJSONObject: ["expression": script, "returnByValue": true])
- var answered = false
- let finish: (String) -> Void = { line in
- guard !answered else { return }
- answered = true
- completion(line)
- }
- // A hung renderer never answers; that is an answer too.
- DispatchQueue.main.asyncAfter(deadline: .now() + 3) { finish("no answer in 3 s (renderer busy or gone)") }
- browser.sendDevToolsMethod("Runtime.evaluate", params: body.flatMap { String(data: $0, encoding: .utf8) } ?? "{}") { result, error in
- DispatchQueue.main.async {
- guard let data = result?.data(using: .utf8),
- let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
- let value = (json["result"] as? [String: Any])?["value"] as? String,
- let fields = (try? JSONSerialization.jsonObject(with: Data(value.utf8))) as? [String: Any] else {
- finish("probe failed: \(error ?? "no result")")
- return
- }
- finish(["blank", "ready", "visibility", "viewport", "scrollHeight", "elements", "text", "painted"]
- .map { "\($0)=\(fields[$0].map { "\($0)" } ?? "?")" }.joined(separator: " "))
- }
- }
- }
-
- /// Where Cra put the page: its view's size and whether anything hides it.
- static func viewState(_ rt: TabRuntime) -> String {
- var views = [rt.browser.containerView]
- if let host = rt.hostWindow {
- views = EmbeddedPages.pageViews(of: host) ?? [host.contentView].compactMap { $0 }
- }
- let shown = views.map { v -> String in
- let hidden = sequence(first: v, next: \.superview).contains { $0.isHidden }
- return "\(Int(v.frame.width))x\(Int(v.frame.height))\(hidden ? " hidden" : "")\(v.window == nil ? " no-window" : "")"
- }
- var s = "view=\(shown.joined(separator: ","))"
- if let host = rt.hostWindow {
- s += " pageWindow=\(host.isVisible ? "visible" : "not visible")\(EmbeddedPages.isHost(host) ? " embedded" : "") alpha=\(host.alphaValue)"
- }
- // Chromium reports a page in a covered window as hidden (visibility=hidden), which is
- // fine; hidden in a window on screen is not.
- if let w = views.first?.window {
- s += " window=\(w.occlusionState.contains(.visible) ? "on screen" : "covered")\(NSApp.isActive ? "" : " app=inactive")"
- }
- return s
- }
-}
-
/// Help ▸ Export Diagnostics…: a zip a user can attach to an issue or send by mail. Holds
/// Cra's and Chromium's logs (this launch and the last), the on-screen pages' state, the GPU
/// report and recent crash reports. Addresses are cut to their host and the home folder to
diff --git a/Sources/Cra/Services/ExtensionStore.swift b/Sources/Cra/Services/ExtensionStore.swift
index b01338e..e8d0337 100644
--- a/Sources/Cra/Services/ExtensionStore.swift
+++ b/Sources/Cra/Services/ExtensionStore.swift
@@ -112,7 +112,15 @@ final class ExtensionStore {
if !e.isEnabled { managed[i].disabledProfiles.insert(profile) }
}
}
- entries = list + managed.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
+ let next = list + managed.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
+ // chrome://extensions switches, in the log: a report of a click on a turned-off extension
+ // shows when Cra learned about it.
+ for e in next {
+ guard let old = entries.first(where: { $0.extensionID == e.extensionID }) else { continue }
+ for p in e.disabledProfiles.subtracting(old.disabledProfiles).sorted() { CraLog.note("extension \(e.extensionID) turned off in \(p)") }
+ for p in old.disabledProfiles.subtracting(e.disabledProfiles).sorted() { CraLog.note("extension \(e.extensionID) turned on in \(p)") }
+ }
+ entries = next
pinnedIDs.removeAll { id in !entries.contains { $0.extensionID == id } }
}
diff --git a/Sources/Cra/Services/Import/Importers.swift b/Sources/Cra/Services/Import/Importers.swift
index bd059ea..73d1aad 100644
--- a/Sources/Cra/Services/Import/Importers.swift
+++ b/Sources/Cra/Services/Import/Importers.swift
@@ -109,8 +109,9 @@ private func pairs(_ list: Any?) -> [(String, [String: Any])] {
// MARK: - Arc
enum ArcImporter {
- static let supportDir = FileManager.default.homeDirectoryForCurrentUser
- .appendingPathComponent("Library/Application Support/Arc", isDirectory: true)
+ /// CRA_ARC_DIR points a test instance at a made-up profile (Tests/Fixtures/Arc).
+ static let supportDir = ProcessInfo.processInfo.environment["CRA_ARC_DIR"].map { URL(fileURLWithPath: $0, isDirectory: true) }
+ ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support/Arc", isDirectory: true)
static var isAvailable: Bool { FileManager.default.fileExists(atPath: supportDir.appendingPathComponent("StorableSidebar.json").path) }
diff --git a/Sources/Cra/Services/LiveFolderManager.swift b/Sources/Cra/Services/LiveFolderManager.swift
index 1bb3907..d796178 100644
--- a/Sources/Cra/Services/LiveFolderManager.swift
+++ b/Sources/Cra/Services/LiveFolderManager.swift
@@ -16,7 +16,7 @@ final class LiveFolderManager {
/// Repositories in each folder's last results plus the hidden ones: the folder menu's list
/// (Arc: "This list is generated based on your currently active pull requests.").
private(set) var repositories: [UUID: [String]] = [:]
- @ObservationIgnored private var timer: Timer?
+ @ObservationIgnored private var timer: ScheduledWork?
/// The last address each tab reported, to tell what a page came from.
@ObservationIgnored private var lastURL: [UUID: String] = [:]
@@ -40,11 +40,9 @@ final class LiveFolderManager {
func start(store: SidebarStore) {
self.store = store
- timer = Timer.scheduledTimer(withTimeInterval: 15, repeats: true) { [weak self] _ in
- Task { @MainActor in
- self?.store?.expireLiveItems(olderThan: Self.retention)
- self?.refreshStale()
- }
+ timer = store.clock.every(15) { [weak self] in
+ self?.store?.expireLiveItems(olderThan: Self.retention)
+ self?.refreshStale()
}
// Dia's windowFocus trigger. App activation makes a window key too.
NotificationCenter.default.addObserver(forName: NSWindow.didBecomeKeyNotification, object: nil, queue: .main) { [weak self] _ in
@@ -57,11 +55,11 @@ final class LiveFolderManager {
/// Dia waits for an active window (LiveDataRefreshSkipReason.waitingForActiveWindow): nothing
/// is fetched while Cra is in the background.
func refreshStale(olderThan age: TimeInterval = refreshInterval) {
- guard NSApp.isActive else { return }
- for f in store?.liveFolders ?? [] {
+ guard NSApp.isActive, let store else { return }
+ for f in store.liveFolders {
let last = f.liveFolder?.lastFetch ?? .distantPast
let failing = f.liveFolder.map { $0.lastError != nil || Self.needsSignIn($0) } ?? false
- if Date().timeIntervalSince(last) >= (failing ? min(age, Self.retryInterval) : age) { refresh(f.id) }
+ if store.clock.now.timeIntervalSince(last) >= (failing ? min(age, Self.retryInterval) : age) { refresh(f.id) }
}
}
@@ -73,7 +71,7 @@ final class LiveFolderManager {
/// `force` skips the gap between refreshes: the folder's filters just changed.
func refresh(_ id: UUID, force: Bool = false) {
guard let store, let live = store.item(id)?.liveFolder, !refreshing.contains(id) else { return }
- if !force, let last = live.lastFetch, Date().timeIntervalSince(last) < Self.minimumInterval, live.lastError == nil { return }
+ if !force, let last = live.lastFetch, store.clock.now.timeIntervalSince(last) < Self.minimumInterval, live.lastError == nil { return }
let attributes: [GitHubLiveFilter.Attributes] = [.authored, .reviewRequests, .teamReviewRequests]
.filter { live.filter.attributes.contains($0) }
refreshing.insert(id)
@@ -137,9 +135,10 @@ final class LiveFolderManager {
private func checkSignIn() {
signInCheck?.cancel()
let work = DispatchWorkItem { [weak self] in
- for f in self?.store?.liveFolders ?? [] where f.liveFolder.map(Self.needsSignIn) ?? false {
+ guard let store = self?.store else { return }
+ for f in store.liveFolders where f.liveFolder.map(Self.needsSignIn) ?? false {
let last = f.liveFolder?.lastFetch ?? .distantPast
- if Date().timeIntervalSince(last) >= Self.minimumInterval { self?.refresh(f.id, force: true) }
+ if store.clock.now.timeIntervalSince(last) >= Self.minimumInterval { self?.refresh(f.id, force: true) }
}
}
signInCheck = work
diff --git a/Sources/Cra/Services/PageProbe.swift b/Sources/Cra/Services/PageProbe.swift
new file mode 100644
index 0000000..f1915e3
--- /dev/null
+++ b/Sources/Cra/Services/PageProbe.swift
@@ -0,0 +1,66 @@
+import AppKit
+import CraCEF
+
+/// What a page holds, asked from the page itself: a blank tab tells apart a navigation that
+/// never committed (about:blank), a page Chromium thinks is hidden, one that has content but
+/// never painted it, and one that is simply empty.
+@MainActor
+enum PageProbe {
+ private static let script = """
+ JSON.stringify({blank: location.href === 'about:blank', ready: document.readyState, visibility: document.visibilityState,
+ viewport: innerWidth + 'x' + innerHeight + '@' + devicePixelRatio,
+ scrollHeight: document.documentElement ? document.documentElement.scrollHeight : 0,
+ elements: document.getElementsByTagName('*').length,
+ text: document.body ? document.body.textContent.length : -1,
+ painted: performance.getEntriesByName('first-contentful-paint').length > 0})
+ """
+
+ /// One line ("ready=complete visibility=visible …"), or why there is none.
+ static func run(_ browser: CraBrowser, completion: @escaping (String) -> Void) {
+ guard browser.isCreated, !browser.isClosed else { completion("no browser yet"); return }
+ let body = try? JSONSerialization.data(withJSONObject: ["expression": script, "returnByValue": true])
+ var answered = false
+ let finish: (String) -> Void = { line in
+ guard !answered else { return }
+ answered = true
+ completion(line)
+ }
+ // A hung renderer never answers; that is an answer too.
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) { finish("no answer in 3 s (renderer busy or gone)") }
+ browser.sendDevToolsMethod("Runtime.evaluate", params: body.flatMap { String(data: $0, encoding: .utf8) } ?? "{}") { result, error in
+ DispatchQueue.main.async {
+ guard let data = result?.data(using: .utf8),
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let value = (json["result"] as? [String: Any])?["value"] as? String,
+ let fields = (try? JSONSerialization.jsonObject(with: Data(value.utf8))) as? [String: Any] else {
+ finish("probe failed: \(error ?? "no result")")
+ return
+ }
+ finish(["blank", "ready", "visibility", "viewport", "scrollHeight", "elements", "text", "painted"]
+ .map { "\($0)=\(fields[$0].map { "\($0)" } ?? "?")" }.joined(separator: " "))
+ }
+ }
+ }
+
+ /// Where Cra put the page: its view's size and whether anything hides it.
+ static func viewState(_ rt: TabRuntime) -> String {
+ var views = [rt.browser.containerView]
+ if let host = rt.hostWindow {
+ views = EmbeddedPages.pageViews(of: host) ?? [host.contentView].compactMap { $0 }
+ }
+ let shown = views.map { v -> String in
+ let hidden = sequence(first: v, next: \.superview).contains { $0.isHidden }
+ return "\(Int(v.frame.width))x\(Int(v.frame.height))\(hidden ? " hidden" : "")\(v.window == nil ? " no-window" : "")"
+ }
+ var s = "view=\(shown.joined(separator: ","))"
+ if let host = rt.hostWindow {
+ s += " pageWindow=\(host.isVisible ? "visible" : "not visible")\(EmbeddedPages.isHost(host) ? " embedded" : "") alpha=\(host.alphaValue)"
+ }
+ // Chromium reports a page in a covered window as hidden (visibility=hidden), which is
+ // fine; hidden in a window on screen is not.
+ if let w = views.first?.window {
+ s += " window=\(w.occlusionState.contains(.visible) ? "on screen" : "covered")\(NSApp.isActive ? "" : " app=inactive")"
+ }
+ return s
+ }
+}
diff --git a/Sources/Cra/Services/Persistence.swift b/Sources/Cra/Services/Persistence.swift
index fc93f1e..e1eeb47 100644
--- a/Sources/Cra/Services/Persistence.swift
+++ b/Sources/Cra/Services/Persistence.swift
@@ -69,10 +69,12 @@ final class JSONStore<T: Codable> {
func load(or fallback: () -> T) -> T {
guard let data = try? Data(contentsOf: url) else { return fallback() }
- if let v = try? decoder.decode(T.self, from: data) { return v }
- // Corrupt file: keep it aside for forensics and start fresh.
- try? FileManager.default.moveItem(at: url, to: url.appendingPathExtension("corrupt"))
- return fallback()
+ do { return try decoder.decode(T.self, from: data) } catch {
+ // Corrupt file: keep it aside for forensics and start fresh.
+ CraLog.fault("\(url.lastPathComponent) unreadable, set aside as .corrupt: \(error)")
+ try? FileManager.default.moveItem(at: url, to: url.appendingPathExtension("corrupt"))
+ return fallback()
+ }
}
func save(_ value: T, delay: TimeInterval = 0.4) {
@@ -90,13 +92,19 @@ final class JSONStore<T: Codable> {
}
private func write(_ value: T) {
- guard let data = try? encoder.encode(value) else { return }
+ let data: Data
+ do { data = try encoder.encode(value) } catch {
+ CraLog.fault("\(url.lastPathComponent) not saved, encoding failed: \(error)")
+ return
+ }
let fm = FileManager.default
let bak = url.appendingPathExtension("bak")
if fm.fileExists(atPath: url.path) {
try? fm.removeItem(at: bak)
try? fm.copyItem(at: url, to: bak)
}
- try? data.write(to: url, options: .atomic)
+ do { try data.write(to: url, options: .atomic) } catch {
+ CraLog.fault("\(url.lastPathComponent) not saved: \(error.localizedDescription)")
+ }
}
}
diff --git a/Sources/Cra/Services/Scheduler.swift b/Sources/Cra/Services/Scheduler.swift
new file mode 100644
index 0000000..5b733eb
--- /dev/null
+++ b/Sources/Cra/Services/Scheduler.swift
@@ -0,0 +1,51 @@
+import Foundation
+
+/// The clock behind every decision Cra makes from time: auto-archive, tab sleep, live folder
+/// expiry, the command file poll. The app runs on `LiveScheduler`; a test host passes a manual
+/// one and advances it, so a 30-minute timer runs in a millisecond (Tests/Support/ManualScheduler).
+/// Animation and hover delays stay on Timer: they perform, they don't decide.
+@MainActor
+protocol Scheduler: AnyObject {
+ var now: Date { get }
+ @discardableResult func after(_ delay: TimeInterval, _ work: @escaping @MainActor () -> Void) -> ScheduledWork
+ @discardableResult func every(_ interval: TimeInterval, _ work: @escaping @MainActor () -> Void) -> ScheduledWork
+}
+
+/// Cancels the work it came from; letting it go does not.
+@MainActor
+final class ScheduledWork {
+ private var onCancel: (() -> Void)?
+ private(set) var isCancelled = false
+ init(onCancel: @escaping () -> Void) { self.onCancel = onCancel }
+ func cancel() {
+ guard !isCancelled else { return }
+ isCancelled = true
+ onCancel?()
+ onCancel = nil
+ }
+}
+
+@MainActor
+final class LiveScheduler: Scheduler {
+ static let shared = LiveScheduler()
+
+ var now: Date { Date() }
+
+ func after(_ delay: TimeInterval, _ work: @escaping @MainActor () -> Void) -> ScheduledWork {
+ timer(delay, repeats: false, work)
+ }
+
+ func every(_ interval: TimeInterval, _ work: @escaping @MainActor () -> Void) -> ScheduledWork {
+ timer(interval, repeats: true, work)
+ }
+
+ private func timer(_ interval: TimeInterval, repeats: Bool, _ work: @escaping @MainActor () -> Void) -> ScheduledWork {
+ var timer: Timer?
+ let handle = ScheduledWork { timer?.invalidate() }
+ // A fire already queued on the main actor when the work is cancelled does not run.
+ timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: repeats) { [weak handle] _ in
+ Task { @MainActor in if let handle, !handle.isCancelled { work() } }
+ }
+ return handle
+ }
+}
diff --git a/Sources/Cra/Services/SidebarIntegrity.swift b/Sources/Cra/Services/SidebarIntegrity.swift
new file mode 100644
index 0000000..9ad7cb6
--- /dev/null
+++ b/Sources/Cra/Services/SidebarIntegrity.swift
@@ -0,0 +1,50 @@
+import Foundation
+
+extension SidebarStore {
+ /// What must hold between any two mutations: a child points back at the parent that lists
+ /// it, nothing is listed twice, every item hangs under a space's container, and a window's
+ /// selected tab lives in the space it is selected for. Empty when the sidebar is sound.
+ /// Scenarios check it at the end of a journey (cra://debug?checkStore=1, one fault line
+ /// per problem) and the store tests after each kind of change.
+ func integrityProblems() -> [String] {
+ let all = items.all
+ func name(_ id: UUID) -> String { String(id.uuidString.prefix(8)) }
+ var problems: [String] = []
+ var listedBy: [UUID: UUID] = [:]
+ for (id, it) in all {
+ for c in it.children {
+ if let other = listedBy[c], other != id { problems.append("\(name(c)) is listed by both \(name(other)) and \(name(id))") }
+ listedBy[c] = id
+ guard let child = all[c] else { problems.append("\(name(id)) lists missing item \(name(c))"); continue }
+ if child.parentID != id { problems.append("\(name(c)) is listed by \(name(id)) but points at \(child.parentID.map(name) ?? "nothing")") }
+ }
+ if Set(it.children).count != it.children.count { problems.append("\(name(id)) lists a child twice") }
+ }
+ for (id, it) in all {
+ if let p = it.parentID {
+ if all[p] == nil { problems.append("\(name(id)) points at missing parent \(name(p))") }
+ else if listedBy[id] == nil { problems.append("\(name(id)) is not listed by its parent \(name(p))") }
+ } else if it.container == nil {
+ problems.append("\(name(id)) hangs under nothing")
+ }
+ // A cycle would hang every walk up the tree (rootContainer, spaceID).
+ var seen: Set<UUID> = [id]
+ var up = it.parentID
+ while let p = up {
+ guard seen.insert(p).inserted else { problems.append("\(name(id)) is inside its own subtree"); break }
+ up = all[p]?.parentID
+ }
+ }
+ for space in spaces.values {
+ for c in [space.favoritesContainerID, space.pinnedContainerID, space.todayContainerID] where all[c]?.container == nil {
+ problems.append("space \(name(space.id)) has no container \(name(c))")
+ }
+ }
+ for w in prefs.windows {
+ for (sid, tid) in w.selectedTabPerSpace where all[tid] != nil && spaceID(ofItem: tid) != sid {
+ problems.append("window \(name(w.id)) selects \(name(tid)) for space \(name(sid)), but it lives elsewhere")
+ }
+ }
+ return problems.sorted()
+ }
+}
diff --git a/Sources/Cra/Services/SidebarStore.swift b/Sources/Cra/Services/SidebarStore.swift
index e7cf99e..a680dd9 100644
--- a/Sources/Cra/Services/SidebarStore.swift
+++ b/Sources/Cra/Services/SidebarStore.swift
@@ -48,8 +48,11 @@ final class SidebarStore {
private let settingsStore = JSONStore<AppSettings>("settings.json")
private let historyFile = JSONStore<[HistoryEntry]>("history.json")
private let rankingFile = JSONStore<RankingData>("commandbar.json")
+ /// Every date the store stamps or compares (AppComposition passes the app's clock).
+ @ObservationIgnored let clock: Scheduler
- init() {
+ init(clock: Scheduler? = nil) {
+ self.clock = clock ?? LiveScheduler.shared
let doc = sidebarFile.load(or: SidebarDocument.fresh)
for s in doc.spaces { spaces[s.id] = s }
profiles = doc.profiles ?? []
@@ -224,7 +227,7 @@ final class SidebarStore {
let today = SidebarItem.container(.today(spaceID: id))
for c in [favorites, pinned, today] { items[c.id] = c }
spaces[id] = Space(id: id, title: "Incognito", emoji: "🕶️", theme: .incognito, favoritesContainerID: favorites.id,
- pinnedContainerID: pinned.id, todayContainerID: today.id, createdAt: Date())
+ pinnedContainerID: pinned.id, todayContainerID: today.id, createdAt: clock.now)
incognitoSpaceIDs.insert(id)
let w = WindowSession(focusedSpaceID: id, frame: frame, isIncognito: true)
prefs.windows.append(w)
@@ -400,18 +403,18 @@ final class SidebarStore {
}
var updated = it
updated.isUnread = false
- if var t = updated.tab { t.timeLastActiveAt = Date(); updated.data = .tab(t) }
+ if var t = updated.tab { t.timeLastActiveAt = clock.now; updated.data = .tab(t) }
items[id] = updated
// Selecting a pane focuses it inside its split (Arc: focusItemID).
if let p = it.parentID, var split = items[p], var s = split.split {
s.focusTabID = id
- s.timeLastActiveAt = Date()
+ s.timeLastActiveAt = clock.now
split.data = .split(s)
items[p] = split
}
if !isIncognito(space: sid) {
var dates = ranking.recentlySwitchedToTabs[id] ?? []
- dates.append(Date())
+ dates.append(clock.now)
if dates.count > 10 { dates.removeFirst(dates.count - 10) }
ranking.recentlySwitchedToTabs[id] = dates
rankingFile.save(ranking)
@@ -507,7 +510,7 @@ final class SidebarStore {
/// sidebar slot, so `sourceSpaceID` is nil and restore uses the focused space.
func archiveLittleWindowPage(url: String, title: String) {
let it = SidebarItem.tab(url, title: title, parent: nil)
- archive.insert(ArchivedItem(archivedAt: Date(), reason: .manual, sourceSpaceID: nil, wasPinned: false, item: it, fromLittleWindow: true), at: 0)
+ archive.insert(ArchivedItem(archivedAt: clock.now, reason: .manual, sourceSpaceID: nil, wasPinned: false, item: it, fromLittleWindow: true), at: 0)
if archive.count > 2000 { archive.removeLast(archive.count - 2000) }
touch()
}
@@ -674,7 +677,7 @@ final class SidebarStore {
}
var split = SidebarItem.split(parent: parentID)
var s = SplitData()
- s.timeLastActiveAt = Date()
+ s.timeLastActiveAt = clock.now
split.data = .split(s)
items[split.id] = split
var p = items[parentID]!
@@ -1102,7 +1105,7 @@ final class SidebarStore {
t.liveSubtitle = subtitle
tab.data = .tab(t)
tab.isUnread = !firstFill
- tab.createdAt = pr.createdAt ?? Date()
+ tab.createdAt = pr.createdAt ?? clock.now
items[tab.id] = tab
order.append(tab.id)
}
@@ -1113,13 +1116,13 @@ final class SidebarStore {
for id in existing.values {
guard var it = items[id], var t = it.tab, t.liveGoneAt == nil else { continue }
if let url = t.liveItemURL, let p = GitHubLiveClient.pullPath(url), ssoHidden.contains(p.owner.lowercased()) { continue }
- t.liveGoneAt = Date()
+ t.liveGoneAt = clock.now
it.data = .tab(t)
items[id] = it
}
folder = items[folderID] ?? folder
folder.children = order + folder.children.filter { !order.contains($0) && items[$0] != nil }
- live.lastFetch = Date()
+ live.lastFetch = clock.now
live.lastError = nil
live.ssoOrganizations = ssoOrganizations
folder.liveFolder = live
@@ -1134,7 +1137,7 @@ final class SidebarStore {
var changed = false
for folder in liveFolders {
for c in children(of: folder.id) where !open.contains(c.id) {
- guard let goneAt = c.tab?.liveGoneAt, Date().timeIntervalSince(goneAt) >= age else { continue }
+ guard let goneAt = c.tab?.liveGoneAt, clock.now.timeIntervalSince(goneAt) >= age else { continue }
detach(c.id)
items[c.id] = nil
changed = true
@@ -1154,7 +1157,7 @@ final class SidebarStore {
func applyLiveFailure(_ error: LiveFolderError, to folderID: UUID) {
updateLiveFolder(folderID) {
- $0.lastFetch = Date()
+ $0.lastFetch = clock.now
$0.lastError = error
}
}
@@ -1192,7 +1195,7 @@ final class SidebarStore {
items[id] = nil
// Empty panes never had a page and incognito pages leave no trace: nothing for the Library.
if !it.isEmptyTab, !isIncognito(space: sid) {
- archive.insert(ArchivedItem(archivedAt: Date(), reason: reason, sourceSpaceID: sid, wasPinned: pinned, item: it,
+ archive.insert(ArchivedItem(archivedAt: clock.now, reason: reason, sourceSpaceID: sid, wasPinned: pinned, item: it,
sourceFolderID: folder, sourceIndex: index), at: 0)
if archive.count > 2000 { archive.removeLast(archive.count - 2000) }
}
@@ -1279,7 +1282,7 @@ final class SidebarStore {
/// ArchiveState+AutoArchive, autoArchiveTimeThreshold).
func runAutoArchive() {
guard settings.autoArchiveEnabled else { return }
- let cutoff = Date().addingTimeInterval(-settings.autoArchive.seconds)
+ let cutoff = clock.now.addingTimeInterval(-settings.autoArchive.seconds)
for space in orderedSpaces {
let selected = Set(prefs.windows.compactMap { $0.selectedTabPerSpace[space.id] })
for t in tabs(under: space.todayContainerID) where !selected.contains(t.id) {
@@ -1302,7 +1305,7 @@ final class SidebarStore {
items[today.id] = today
let t = theme ?? SpaceTheme.presets[spaceOrder.count % SpaceTheme.presets.count]
let space = Space(id: id, title: title, emoji: emoji, theme: t, favoritesContainerID: favorites.id,
- pinnedContainerID: pinned.id, todayContainerID: today.id, createdAt: Date())
+ pinnedContainerID: pinned.id, todayContainerID: today.id, createdAt: clock.now)
spaces[id] = space
spaceOrder.append(id)
if focus, !window().isIncognito { updateWindow(nil) { $0.focusedSpaceID = id } }
@@ -1433,9 +1436,9 @@ final class SidebarStore {
func recordVisit(url: String, title: String) {
guard url.hasPrefix("http") else { return }
- var e = history[url] ?? HistoryEntry(url: url, title: title, lastVisit: Date(), visitCount: 0)
+ var e = history[url] ?? HistoryEntry(url: url, title: title, lastVisit: clock.now, visitCount: 0)
e.visitCount += 1
- e.lastVisit = Date()
+ e.lastVisit = clock.now
if !title.isEmpty { e.title = title }
history[url] = e
if history.count > 5000 {
diff --git a/Sources/Cra/Services/SoftwareUpdater.swift b/Sources/Cra/Services/SoftwareUpdater.swift
index 047412e..03fbab5 100644
--- a/Sources/Cra/Services/SoftwareUpdater.swift
+++ b/Sources/Cra/Services/SoftwareUpdater.swift
@@ -76,7 +76,7 @@ final class SoftwareUpdater: NSObject {
@ObservationIgnored private var choiceReply: ((SPUUserUpdateChoice) -> Void)?
@ObservationIgnored private var cancellation: (() -> Void)?
@ObservationIgnored private var acknowledgement: (() -> Void)?
- @ObservationIgnored private var autoRestartTimer: Timer?
+ @ObservationIgnored private var autoRestartTimer: ScheduledWork?
@ObservationIgnored private var inactiveSince: Date?
private enum Keys {
@@ -225,9 +225,9 @@ final class SoftwareUpdater: NSObject {
/// duration-in-seconds); Cra waits until the user is away: Cra in the background for 10
/// minutes and no input for 2, or no input at all for 30.
private func scheduleAutoRestart() {
- autoRestartTimer?.invalidate()
- autoRestartTimer = Timer.scheduledTimer(withTimeInterval: max(1, min(60, quickRestart ?? 60)), repeats: true) { [weak self] _ in
- MainActor.assumeIsolated { self?.considerAutoRestart() }
+ autoRestartTimer?.cancel()
+ autoRestartTimer = (app?.composition.clock ?? LiveScheduler.shared).every(max(1, min(60, quickRestart ?? 60))) { [weak self] in
+ self?.considerAutoRestart()
}
}
diff --git a/Sources/Cra/Services/ViewSnapshot.swift b/Sources/Cra/Services/ViewSnapshot.swift
new file mode 100644
index 0000000..3c8ffdd
--- /dev/null
+++ b/Sources/Cra/Services/ViewSnapshot.swift
@@ -0,0 +1,52 @@
+import AppKit
+
+/// Component snapshots (scripts/scenario.sh `snapshot`): a view of the running window, found by its
+/// class, drawn into a PNG from its layer tree at 2x. Behind-window blur and page content are
+/// not part of a layer tree, so the picture holds Cra's own drawing only: geometry, ink, fills.
+@MainActor
+enum ViewSnapshot {
+ /// "PaneToolbarView" or "PaneToolbarView,1": the first (or nth) view of that class on screen
+ /// in the window, left to right and top to bottom (the pager keeps other spaces' columns
+ /// laid out beside the visible one).
+ static func write(_ spec: String, in window: NSWindow?, to path: String) {
+ let parts = spec.split(separator: ",").map(String.init)
+ guard let root = window?.contentView?.superview ?? window?.contentView else { return }
+ var found: [NSView] = []
+ func walk(_ v: NSView) {
+ if String(describing: type(of: v)) == parts[0], !v.isHiddenOrHasHiddenAncestor, !v.visibleRect.isEmpty,
+ v.convert(v.bounds, to: nil).intersects(root.bounds) { found.append(v) }
+ v.subviews.forEach(walk)
+ }
+ walk(root)
+ found.sort {
+ let a = $0.convert($0.bounds, to: nil), b = $1.convert($1.bounds, to: nil)
+ return (a.minX, -a.maxY) < (b.minX, -b.maxY)
+ }
+ let index = parts.count > 1 ? Int(parts[1]) ?? 0 : 0
+ guard index < found.count, let png = render(found[index]) else {
+ CraLog.note("snapshot: no visible \(spec)")
+ return
+ }
+ do { try png.write(to: URL(fileURLWithPath: path)) } catch { CraLog.note("snapshot: \(error.localizedDescription)") }
+ }
+
+ private static func render(_ view: NSView) -> Data? {
+ view.layoutSubtreeIfNeeded()
+ view.displayIfNeeded()
+ guard let layer = view.layer else { return nil }
+ let scale: CGFloat = 2
+ let w = Int(view.bounds.width * scale), h = Int(view.bounds.height * scale)
+ guard let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: 0,
+ space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
+ else { return nil }
+ ctx.scaleBy(x: scale, y: scale)
+ // The context's origin is at the bottom left; a flipped view's layer draws from the top.
+ if layer.isGeometryFlipped || view.isFlipped {
+ ctx.translateBy(x: 0, y: view.bounds.height)
+ ctx.scaleBy(x: 1, y: -1)
+ }
+ layer.render(in: ctx)
+ guard let image = ctx.makeImage() else { return nil }
+ return NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:])
+ }
+}
diff --git a/Sources/Cra/UI/PaneToolbarView.swift b/Sources/Cra/UI/PaneToolbarView.swift
index e41b5da..47b00b2 100644
--- a/Sources/Cra/UI/PaneToolbarView.swift
+++ b/Sources/Cra/UI/PaneToolbarView.swift
@@ -17,7 +17,7 @@ final class PaneToolbarView: NSView {
private let actions: SidebarActions
private struct Model: Equatable {
- enum Kind: Equatable { case noTab, emptyPane, normal, developer }
+ typealias Kind = ToolbarComposition.Kind
struct Ext: Equatable { let id: String; let name: String; let icon: NSImage? }
var kind = Kind.noTab
var inSplit = false
@@ -217,57 +217,51 @@ final class PaneToolbarView: NSView {
(superview as? PaneCardView)?.developerBar = m.kind == .developer ? m.fill : nil
hairline.isHidden = m.hairline == nil
hairline.layer?.backgroundColor = m.hairline?.cgColor
- var l: [ToolbarGlyphButton] = []
- var r: [NSView] = []
- let toggle = { self.glyph("toggle", "sidebar.left", help: m.sidebarVisible ? "Hide Sidebar (⌘S)" : "Show Sidebar (⌘S)",
- width: 37, iconSize: 15.5) { $0.actions.toggleSidebar() } }
- switch m.kind {
- case .noTab:
- l = [toggle(),
- glyph("back", "arrow.left", help: "", enabled: false, width: 37, iconSize: 15) { _ in },
- glyph("forward", "arrow.right", help: "", enabled: false, width: 37, iconSize: 15) { _ in },
- glyph("reload", "arrow.clockwise", help: "", enabled: false, width: 37, iconSize: 15) { _ in }]
- case .emptyPane:
- l = [glyph("back", "arrow.left", help: "", enabled: false, width: 37, iconSize: 15) { _ in },
- glyph("forward", "arrow.right", help: "", enabled: false, width: 37, iconSize: 15) { _ in }]
- case .normal:
- // Toggle first, centred 30 pt from the card edge (Arc, sidebar hidden), then ← → ↻ at 37 pt
- // pitch. Split panes drop the toggle and refresh (Arc 1.170: only ← → in a pane).
- if !m.inSplit { l.append(toggle()) }
- l.append(glyph("back", "arrow.left", help: "Go Back (⌘[)", enabled: m.canGoBack, width: 37, iconSize: 15) { $0.navigate("goBack") })
- l.append(glyph("forward", "arrow.right", help: "Go Forward (⌘])", enabled: m.canGoForward, width: 37, iconSize: 15) { $0.navigate("goForward") })
- if !m.inSplit {
- l.append(glyph("reload", m.isLoading ? "xmark" : "arrow.clockwise", help: "Refresh (⌘R)", width: 37, iconSize: 15,
- animated: true) { $0.navigate("reload") })
- }
- case .developer:
- if !m.inSplit { l.append(toggle()) }
- r.append(glyph("copy", "link", help: "Copy URL (⇧⌘C)", width: 28) { $0.actions.performAction("copyURL") })
- r.append(devDivider)
- r.append(glyph("devtools", "terminal", help: "Developer Tools (⌥⌘I)", width: 28) { $0.actions.performAction("devTools") })
- }
- // Arc's right end of the bar: pinned extensions, the Extensions button, then Split View;
- // also on the no-tab bar. A split pane has its options (focused pane only) and close.
- if !m.inSplit, m.kind != .emptyPane {
- for e in m.pinned {
- let b = button("ext:" + e.id) { ToolbarGlyphButton() }
- b.configure(symbol: nil, image: e.icon, help: e.name, enabled: true, width: 34, iconSize: 18, tint: m.fgDim, hover: m.hover)
- let id = e.id
+ let bar = ToolbarComposition(kind: m.kind, inSplit: m.inSplit, focusedPane: m.focusedPane, canGoBack: m.canGoBack,
+ canGoForward: m.canGoForward, isLoading: m.isLoading, pinnedExtensions: m.pinned.map(\.id),
+ hasExtensions: m.hasExtensions)
+ // The no-tab bar and an empty pane show navigation that does nothing (Arc greys it out).
+ let wide = m.kind == .noTab || m.kind == .emptyPane
+ func view(_ item: ToolbarComposition.Item) -> NSView {
+ switch item {
+ case .toggleSidebar:
+ return glyph("toggle", "sidebar.left", help: m.sidebarVisible ? "Hide Sidebar (⌘S)" : "Show Sidebar (⌘S)",
+ width: 37, iconSize: 15.5) { $0.actions.toggleSidebar() }
+ case .back(let enabled):
+ return glyph("back", "arrow.left", help: wide ? "" : "Go Back (⌘[)", enabled: enabled, width: 37, iconSize: 15) { if !wide { $0.navigate("goBack") } }
+ case .forward(let enabled):
+ return glyph("forward", "arrow.right", help: wide ? "" : "Go Forward (⌘])", enabled: enabled, width: 37, iconSize: 15) { if !wide { $0.navigate("goForward") } }
+ case .reload(let loading, let enabled):
+ return glyph("reload", loading ? "xmark" : "arrow.clockwise", help: enabled ? "Refresh (⌘R)" : "", enabled: enabled, width: 37,
+ iconSize: 15, animated: enabled) { if !wide { $0.navigate("reload") } }
+ case .copyURL:
+ return glyph("copy", "link", help: "Copy URL (⇧⌘C)", width: 28) { $0.actions.performAction("copyURL") }
+ case .divider:
+ return devDivider
+ case .devTools:
+ return glyph("devtools", "terminal", help: "Developer Tools (⌥⌘I)", width: 28) { $0.actions.performAction("devTools") }
+ case .pinnedExtension(let id):
+ let e = m.pinned.first { $0.id == id }
+ let b = button("ext:" + id) { ToolbarGlyphButton() }
+ b.configure(symbol: nil, image: e?.icon, help: e?.name ?? "", enabled: true, width: 34, iconSize: 18, tint: m.fgDim, hover: m.hover)
b.action = { [weak self] in self?.actions.runExtension(id) }
b.menuProvider = { ExtensionStore.shared.entries.first { $0.extensionID == id }.map(ExtensionsMenu.iconMenu) }
- r.append(b)
- }
- if m.hasExtensions {
- r.append(glyph("extensions", "slider.horizontal.2.square", help: "Extensions", width: 34, iconSize: 16) { $0.actions.showExtensionsMenu() })
- }
- r.append(glyph("split", "square.split.2x1", help: "Add Split View (⌃⇧=)", width: 34, iconSize: 16) { $0.actions.performAction("addSplitView") })
- }
- if m.inSplit, let id = paneTabID {
- if m.focusedPane, m.kind != .emptyPane {
- r.append(glyph("splitOptions", "rectangle.split.2x1", help: "Split View Options") { $0.showSplitMenu(from: $0.buttons["splitOptions"]) })
+ return b
+ case .extensions:
+ return glyph("extensions", "slider.horizontal.2.square", help: "Extensions", width: 34, iconSize: 16) { $0.actions.showExtensionsMenu() }
+ case .addSplit:
+ return glyph("split", "square.split.2x1", help: "Add Split View (⌃⇧=)", width: 34, iconSize: 16) { $0.actions.performAction("addSplitView") }
+ case .splitOptions:
+ return glyph("splitOptions", "rectangle.split.2x1", help: "Split View Options") { $0.showSplitMenu(from: $0.buttons["splitOptions"]) }
+ case .closePane:
+ let id = paneTabID
+ return glyph("close", "xmark", help: "Close this Split Pane (⌃⇧-)", width: 30, iconSize: 14, tint: m.closeTint) {
+ if let id { $0.actions.closePane(id) }
+ }
}
- r.append(glyph("close", "xmark", help: "Close this Split Pane (⌃⇧-)", width: 30, iconSize: 14, tint: m.closeTint) { $0.actions.closePane(id) })
}
+ let l = bar.left.compactMap { view($0) as? ToolbarGlyphButton }
+ let r = bar.right.map(view)
devDivider.layer?.backgroundColor = m.dividerColor.cgColor
let used = Set((l as [NSView] + r).map(ObjectIdentifier.init))
for (k, b) in buttons where !used.contains(ObjectIdentifier(b)) {
diff --git a/Sources/Cra/UI/ShellView.swift b/Sources/Cra/UI/ShellView.swift
index ca34ae9..62b993e 100644
--- a/Sources/Cra/UI/ShellView.swift
+++ b/Sources/Cra/UI/ShellView.swift
@@ -117,6 +117,16 @@ final class ShellView: NSView {
return filter
}
+ /// Which blur path this run takes, once: scenarios run both (CRA_FLAGS) and the
+ /// log says which one a crash or a stall happened on.
+ private static var loggedBackdropPath = false
+ private static func logBackdropPath(layer: Bool) {
+ guard !loggedBackdropPath else { return }
+ loggedBackdropPath = true
+ let why = FeatureFlags.current.backdrop == .material ? "CRA_FLAGS" : "no CABackdropLayer or CAFilter"
+ CraLog.note("sidebar backdrop: " + (layer ? "layer" : "material (\(why))"))
+ }
+
func refreshLift() {
let t = CraTuning.shared
let lift = vibrantDark ? (windowActive ? 0.15 : 0.93) : (windowActive ? t.liftActive : t.liftInactive)
@@ -169,7 +179,8 @@ final class ShellView: NSView {
// The window server only keeps a behind-window capture live for a layer that is
// window-server aware in AppKit's capture group (NSVisualEffectView's own settings);
// without them the blur showed only while the window was redrawing (GitHub #37).
- if let cls = NSClassFromString("CABackdropLayer") as? CALayer.Type,
+ if FeatureFlags.current.backdrop == .layer,
+ let cls = NSClassFromString("CABackdropLayer") as? CALayer.Type,
let blur = ShellView.makeBackdropBlur(radius: 40) {
let b = cls.init()
b.filters = [blur]
@@ -185,6 +196,7 @@ final class ShellView: NSView {
backdropHost.layer?.addSublayer(liftLayer)
backdropHost.isHidden = true
addSubview(backdropHost)
+ Self.logBackdropPath(layer: backdropLayer != nil)
vibrancyLift.wantsLayer = true
vibrancyLift.layer?.backgroundColor = NSColor(white: 1, alpha: 0.15).cgColor
vibrancyLift.isHidden = true
diff --git a/Sources/Cra/UI/ToolbarComposition.swift b/Sources/Cra/UI/ToolbarComposition.swift
new file mode 100644
index 0000000..56247ff
--- /dev/null
+++ b/Sources/Cra/UI/ToolbarComposition.swift
@@ -0,0 +1,58 @@
+import Foundation
+
+/// Which buttons Arc's toolbar carries, in order, for a pane's state; PaneToolbarView makes
+/// and places the views. Measured against Arc 1.170: the full bar is sidebar toggle ← → ↻ on
+/// the left and pinned extensions, Extensions, Split View on the right; a split pane has only
+/// ← → and its options (focused pane) and close; the developer bar swaps the navigation for
+/// copy · divider · DevTools.
+struct ToolbarComposition: Equatable {
+ enum Kind: Equatable { case noTab, emptyPane, normal, developer }
+
+ enum Item: Equatable {
+ case toggleSidebar
+ case back(enabled: Bool)
+ case forward(enabled: Bool)
+ /// An ✕ while the page loads.
+ case reload(loading: Bool, enabled: Bool)
+ case copyURL
+ case divider
+ case devTools
+ case pinnedExtension(String)
+ case extensions
+ case addSplit
+ case splitOptions
+ case closePane
+ }
+
+ var left: [Item] = []
+ var right: [Item] = []
+
+ init(kind: Kind, inSplit: Bool, focusedPane: Bool, canGoBack: Bool, canGoForward: Bool, isLoading: Bool,
+ pinnedExtensions: [String], hasExtensions: Bool) {
+ switch kind {
+ case .noTab:
+ left = [.toggleSidebar, .back(enabled: false), .forward(enabled: false), .reload(loading: false, enabled: false)]
+ case .emptyPane:
+ left = [.back(enabled: false), .forward(enabled: false)]
+ case .normal:
+ // Split panes drop the toggle and refresh (Arc 1.170: only ← → in a pane).
+ if !inSplit { left.append(.toggleSidebar) }
+ left += [.back(enabled: canGoBack), .forward(enabled: canGoForward)]
+ if !inSplit { left.append(.reload(loading: isLoading, enabled: true)) }
+ case .developer:
+ if !inSplit { left.append(.toggleSidebar) }
+ right += [.copyURL, .divider, .devTools]
+ }
+ // Arc's right end: pinned extensions, the Extensions button, then Split View; also on
+ // the no-tab bar. A split pane has its options (focused pane only) and close instead.
+ if !inSplit, kind != .emptyPane {
+ right += pinnedExtensions.map(Item.pinnedExtension)
+ if hasExtensions { right.append(.extensions) }
+ right.append(.addSplit)
+ }
+ if inSplit {
+ if focusedPane, kind != .emptyPane { right.append(.splitOptions) }
+ right.append(.closePane)
+ }
+ }
+}
diff --git a/Sources/Cra/UI/Windows/ExtensionLaunch.swift b/Sources/Cra/UI/Windows/ExtensionLaunch.swift
new file mode 100644
index 0000000..d6099b6
--- /dev/null
+++ b/Sources/Cra/UI/Windows/ExtensionLaunch.swift
@@ -0,0 +1,37 @@
+import Foundation
+
+/// What a click on an extension's button does (toolbar, sidebar URL pill, Extensions menu,
+/// a shortcut): MainWindowController performs it. Only an extension installed and turned on in
+/// the focused page's profile runs; one turned off in chrome://extensions is out of the toolbar
+/// and the menus (GitHub #41) and must not be reached from a stale button or a shortcut either.
+enum ExtensionLaunch: Equatable {
+ case nothing
+ /// Chrome's action on the focused page; its popup hangs from the toolbar.
+ case runAction
+ /// No page for Chrome's popup to attach to: the popup page in a popup-sized window.
+ case popupWindow(url: String)
+ /// No popup at all: the options page, else Chrome's details page for the extension.
+ case openTab(url: String)
+
+ struct Extension: Equatable {
+ let id: String
+ var popupPath: String?
+ var optionsPath: String?
+ var enabled = true
+ }
+
+ /// `available`: the extensions of the focused page's profile. `hasPage`: a page and a
+ /// toolbar to anchor Chrome's popup.
+ static func decide(_ id: String, available: [Extension], hasPage: Bool) -> ExtensionLaunch {
+ guard let e = available.first(where: { $0.id == id }), e.enabled else { return .nothing }
+ return hasPage ? .runAction : fallback(e)
+ }
+
+ /// Also what follows when Chrome could not run the action on the page.
+ static func fallback(_ e: Extension) -> ExtensionLaunch {
+ guard e.enabled else { return .nothing }
+ let base = "chrome-extension://\(e.id)/"
+ if let popup = e.popupPath { return .popupWindow(url: base + popup) }
+ return .openTab(url: e.optionsPath.map { base + $0 } ?? "chrome://extensions/?id=\(e.id)")
+ }
+}
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index bf0aa7d..f6bc4aa 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -99,7 +99,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
window.contentView = shell
window.backgroundColor = NSColor(palette.gradientColors.first ?? .gray)
- browsers = BrowserManager(store: store, favicons: app.favicons, container: shell.parkingView)
+ browsers = BrowserManager(store: store, favicons: app.favicons, container: shell.parkingView, clock: app.composition.clock)
browsers.delegate = self
browsers.windowID = session.id
browsers.takeRuntimeFromOtherWindow = { [weak self] id in
@@ -1674,16 +1674,32 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
/// Dia's Extensions menu. The popup hangs under the toolbar, its right edge at `buttonRightX`
/// (screen x of the clicked button; nil = the extension's toolbar button or the card's right end).
func runExtensionAction(_ id: String, buttonRightX: CGFloat? = nil) {
- guard extensionEntries.contains(where: { $0.extensionID == id }) else { return }
- guard let bar = toolbarBottomOnScreen() else { openExtensionPopupPage(id, anchor: nil); return }
- let anchor = buttonRightX.map { NSPoint(x: $0, y: urlBarBottomOnScreen() ?? bar.y) }
- ?? extensionPopupAnchor(id) ?? NSPoint(x: bar.cardMaxX - 8, y: bar.y)
- guard let browser = currentBrowser else { openExtensionPopupPage(id, anchor: anchor); return }
- let inDefaultProfile = profileDirectoryName == "Default"
- Task {
- if await !ExtensionActions.shared.run(id, on: browser, anchor: anchor, inDefaultProfile: inDefaultProfile) {
- self.openExtensionPopupPage(id, anchor: anchor)
+ let bar = toolbarBottomOnScreen()
+ let browser = currentBrowser
+ let anchor = bar.map { bar in
+ buttonRightX.map { NSPoint(x: $0, y: urlBarBottomOnScreen() ?? bar.y) } ?? extensionPopupAnchor(id) ?? NSPoint(x: bar.cardMaxX - 8, y: bar.y)
+ }
+ let available = profileExtensions
+ switch ExtensionLaunch.decide(id, available: available, hasPage: bar != nil && browser != nil) {
+ case .nothing: return
+ case .runAction:
+ guard let browser, let anchor else { return }
+ let inDefaultProfile = profileDirectoryName == "Default"
+ Task {
+ if await !ExtensionActions.shared.run(id, on: browser, anchor: anchor, inDefaultProfile: inDefaultProfile),
+ let e = available.first(where: { $0.id == id }) {
+ self.perform(ExtensionLaunch.fallback(e), anchor: anchor)
+ }
}
+ case let fallback: perform(fallback, anchor: anchor)
+ }
+ }
+
+ /// The extensions installed in the focused page's profile, turned on or not.
+ private var profileExtensions: [ExtensionLaunch.Extension] {
+ let profile = profileDirectoryName
+ return ExtensionStore.shared.entries.filter { $0.isInstalled(inProfile: profile) }.map {
+ ExtensionLaunch.Extension(id: $0.extensionID, popupPath: $0.popupPath, optionsPath: $0.optionsPath, enabled: $0.isEnabled(inProfile: profile))
}
}
@@ -1712,16 +1728,16 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
/// No page for Chrome's popup to attach to (no tab open, no DevTools pipe, a page it
- /// cannot reach): the popup page in a popup-sized window under the button, else the
- /// options page, else Chrome's details page for the extension.
- private func openExtensionPopupPage(_ id: String, anchor: NSPoint?) {
- guard let e = ExtensionStore.shared.entries.first(where: { $0.extensionID == id }) else { return }
- let base = "chrome-extension://\(id)/"
- if let popup = e.popupPath {
+ /// cannot reach): ExtensionLaunch picks the popup page in a popup-sized window under the
+ /// button, else the options page, else Chrome's details page for the extension.
+ private func perform(_ launch: ExtensionLaunch, anchor: NSPoint?) {
+ switch launch {
+ case .nothing, .runAction: break
+ case .popupWindow(let url):
let fallback = window.map { NSPoint(x: $0.frame.maxX - 16, y: $0.frame.maxY - CraMetrics.toolbarHeight) } ?? .zero
- ExtensionPageWindow.open(url: base + popup, anchor: anchor ?? fallback, app: app)
- } else {
- store.createTab(url: e.optionsPath.map { base + $0 } ?? "chrome://extensions/?id=\(id)", select: true, window: windowID)
+ ExtensionPageWindow.open(url: url, anchor: anchor ?? fallback, app: app)
+ case .openTab(let url):
+ store.createTab(url: url, select: true, window: windowID)
}
}
diff --git a/Tests/BrowserManagerLifecycleTests.swift b/Tests/BrowserManagerLifecycleTests.swift
index f4b573a..db2c830 100644
--- a/Tests/BrowserManagerLifecycleTests.swift
+++ b/Tests/BrowserManagerLifecycleTests.swift
@@ -77,6 +77,8 @@ enum BrowserManagerLifecycleTests {
await sleepCase("an exception reply cannot authorize sleeping", reply: #"{"exceptionDetails":{},"result":{"value":""}}"#) { _, _ in }
await sleepCase("a page holding typed text stays awake", reply: #"{"result":{"type":"string","value":"typed"}}"#) { _, _ in }
await refusalBackoffCase()
+ await sleepClockCase()
+ devToolsCase()
await beforeUnloadCase()
nowPlayingCase()
await sleepCase("malformed or missing replies cannot authorize sleeping", reply: nil) { _, _ in }
@@ -189,6 +191,56 @@ enum BrowserManagerLifecycleTests {
manager.closeAll()
}
+ /// Tab sleeping on the manager's clock: an hour's threshold and the 10-minute back-off run
+ /// in no time, and nothing is asked a second early.
+ @MainActor
+ private static func sleepClockCase() async {
+ let clock = ManualScheduler()
+ let store = SidebarStore()
+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView(), clock: clock)
+ let id = store.createTab(url: "https://example.test/clock").id
+ let runtime = manager.ensureRuntime(for: id)!
+ func probed() -> Bool { runtime.browser.replies.contains { $0.method == isolatedProbe } }
+ clock.advance(by: 3599)
+ manager.sleepIdleTabs(hiddenLongerThan: 3600)
+ expect(!probed(), "a page hidden a second short of the threshold is not asked")
+ clock.advance(by: 2)
+ manager.sleepIdleTabs(hiddenLongerThan: 3600)
+ expect(probed(), "a page hidden past the threshold is asked")
+ runtime.browser.reply(to: isolatedProbe, with: #"{"result":{"type":"string","value":"typed"}}"#)
+ await drainMainQueue()
+ clock.advance(by: BrowserManager.refusalBackoff - 1)
+ manager.sleepIdleTabs(hiddenLongerThan: 3600)
+ expect(!probed(), "a refused page is not asked again inside the back-off")
+ clock.advance(by: 1)
+ manager.sleepIdleTabs(hiddenLongerThan: 3600)
+ expect(probed(), "a refused page is asked again once the back-off ends")
+ manager.closeAll()
+ }
+
+ /// ⌥⌘I pressed again while CEF is still closing DevTools opens them once they are gone,
+ /// instead of closing them a second time.
+ @MainActor
+ private static func devToolsCase() {
+ let store = SidebarStore()
+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView())
+ let id = store.createTab(url: "https://example.test/devtools").id
+ manager.show(id, focus: false)
+ let browser = manager.runtime(for: id)!.browser
+ manager.toggleDevTools()
+ manager.browser(browser, didCreateDevToolsView: NSView())
+ manager.toggleDevTools()
+ manager.toggleDevTools()
+ expect(browser.devToolsRequests == ["show", "close"], "a press while DevTools close asks CEF for nothing yet")
+ manager.browserDidCloseDevTools(browser)
+ expect(browser.devToolsRequests == ["show", "close", "show"], "once CEF reports them closed, the press opens them again")
+ manager.browser(browser, didCreateDevToolsView: NSView())
+ manager.showDevTools()
+ expect(browser.devToolsRequests.last == "show" && manager.runtime(for: id)!.devTools.state == .open,
+ "Inspect Element on open DevTools keeps them open")
+ manager.closeAll()
+ }
+
/// The page's own onbeforeunload, asked in its world after the isolated probe, keeps it awake.
@MainActor
private static func beforeUnloadCase() async {
diff --git a/Tests/BrowserManagerSupport/AppServices.swift b/Tests/BrowserManagerSupport/AppServices.swift
index 4554800..9795b99 100644
--- a/Tests/BrowserManagerSupport/AppServices.swift
+++ b/Tests/BrowserManagerSupport/AppServices.swift
@@ -43,14 +43,6 @@ final class FaviconCache {
}
enum TabSwitcherMetrics { static let thumbnail = NSSize(width: 320, height: 200) }
enum HitchMonitor { static func mark(_ event: String) {} }
-enum CraLog {
- static func note(_ message: String) {}
- static func host(_ url: String) -> String { URL(string: url)?.host ?? "?" }
-}
-enum PageProbe {
- static func run(_ browser: CraBrowser, completion: @escaping (String) -> Void) {}
- static func viewState(_ runtime: TabRuntime) -> String { "" }
-}
enum EmbeddedPages {
static var viewsByHost: [ObjectIdentifier: [NSView]] = [:]
static func isHost(_ window: NSWindow) -> Bool { viewsByHost[ObjectIdentifier(window)] != nil }
diff --git a/Tests/BrowserManagerSupport/CraCEF.swift b/Tests/BrowserManagerSupport/CraCEF.swift
index 598d72b..9331ae6 100644
--- a/Tests/BrowserManagerSupport/CraCEF.swift
+++ b/Tests/BrowserManagerSupport/CraCEF.swift
@@ -44,7 +44,10 @@ public final class CraBrowser {
public func close() { closeRequested = true; onClose?() }
public func finishClose() { isClosed = true; delegate?.browserDidClose(self) }
- public func closeDevTools() { hasDevTools = false }
+ /// "show" / "close", in the order Cra asked.
+ public var devToolsRequests: [String] = []
+ public func showDevTools() { hasDevTools = true; devToolsRequests.append("show") }
+ public func closeDevTools() { hasDevTools = false; devToolsRequests.append("close") }
public func setAudioMuted(_ muted: Bool) {}
public func setFocused(_ focused: Bool) {}
public func requestPictureInPicture(automatic: Bool) {}
diff --git a/Tests/Fixtures/Arc/README.md b/Tests/Fixtures/Arc/README.md
new file mode 100644
index 0000000..8c96488
--- /dev/null
+++ b/Tests/Fixtures/Arc/README.md
@@ -0,0 +1,4 @@
+A made-up Arc profile in Arc's own file format (Arc 1.170 field names), for the importer
+tests (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.
diff --git a/Tests/Fixtures/Arc/StorableArchiveItems.json b/Tests/Fixtures/Arc/StorableArchiveItems.json
new file mode 100644
index 0000000..b37a688
--- /dev/null
+++ b/Tests/Fixtures/Arc/StorableArchiveItems.json
@@ -0,0 +1,46 @@
+{
+ "items": [
+ {
+ "sidebarItem": {
+ "id": "a1",
+ "title": null,
+ "childrenIds": [],
+ "createdAt": 800000000.0,
+ "data": {
+ "tab": {
+ "savedURL": "https://example.com/old/1",
+ "savedTitle": "Old one"
+ }
+ }
+ },
+ "reason": "auto",
+ "archivedAt": 799996400.0,
+ "source": {
+ "space": {
+ "_0": "home"
+ }
+ }
+ },
+ {
+ "sidebarItem": {
+ "id": "a2",
+ "title": null,
+ "childrenIds": [],
+ "createdAt": 800000000.0,
+ "data": {
+ "tab": {
+ "savedURL": "https://example.com/old/2",
+ "savedTitle": "Old two"
+ }
+ }
+ },
+ "reason": "manual",
+ "archivedAt": 799999940.0,
+ "source": {
+ "space": {
+ "_0": "work"
+ }
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/Tests/Fixtures/Arc/StorableSidebar.json b/Tests/Fixtures/Arc/StorableSidebar.json
new file mode 100644
index 0000000..edc9e67
--- /dev/null
+++ b/Tests/Fixtures/Arc/StorableSidebar.json
@@ -0,0 +1,362 @@
+{
+ "version": 1,
+ "sidebar": {
+ "containers": [
+ {
+ "global": {}
+ },
+ {
+ "spaces": [
+ "home",
+ {
+ "id": "home",
+ "title": "Home",
+ "profile": {
+ "default": true
+ },
+ "containerIDs": [
+ "pinned",
+ "home-pinned",
+ "unpinned",
+ "home-today"
+ ],
+ "customInfo": {
+ "iconType": {
+ "emoji_v2": "🏠"
+ }
+ }
+ },
+ "work",
+ {
+ "id": "work",
+ "title": "Work",
+ "profile": {
+ "default": true
+ },
+ "containerIDs": [
+ "pinned",
+ "work-pinned",
+ "unpinned",
+ "work-today"
+ ],
+ "customInfo": {
+ "iconType": {
+ "emoji": 128188
+ }
+ }
+ }
+ ],
+ "items": [
+ "fav",
+ {
+ "id": "fav",
+ "title": null,
+ "parentID": null,
+ "childrenIds": [
+ "fav-1",
+ "fav-2"
+ ],
+ "isUnread": false,
+ "originatingDevice": "FIXTURE",
+ "createdAt": 800000000.0,
+ "data": {
+ "itemContainer": {
+ "containerType": {
+ "topApps": {
+ "_0": {
+ "default": true
+ }
+ }
+ }
+ }
+ }
+ },
+ "fav-1",
+ {
+ "id": "fav-1",
+ "title": null,
+ "parentID": "fav",
+ "childrenIds": [],
+ "isUnread": false,
+ "originatingDevice": "FIXTURE",
+ "createdAt": 800000000.0,
+ "data": {
+ "tab": {
+ "savedURL": "https://example.com/mail",
+ "savedTitle": "Mail",
+ "savedMuteStatus": "allowAudio",
+ "timeLastActiveAt": 800000000.0
+ }
+ }
+ },
+ "fav-2",
+ {
+ "id": "fav-2",
+ "title": null,
+ "parentID": "fav",
+ "childrenIds": [],
+ "isUnread": false,
+ "originatingDevice": "FIXTURE",
+ "createdAt": 800000000.0,
+ "data": {
+ "tab": {
+ "savedURL": "https://example.com/calendar",
+ "savedTitle": "Calendar",
+ "savedMuteStatus": "allowAudio",
+ "timeLastActiveAt": 800000000.0
+ }
+ }
+ },
+ "home-pinned",
+ {
+ "id": "home-pinned",
+ "title": null,
+ "parentID": null,
+ "childrenIds": [
+ "home-folder"
+ ],
+ "isUnread": false,
+ "originatingDevice": "FIXTURE",
+ "createdAt": 800000000.0,
+ "data": {
+ "itemContainer": {
+ "containerType": {
+ "spaceItems": {
+ "_0": "home"
+ }
+ }
+ }
+ }
+ },
+ "home-folder",
+ {
+ "id": "home-folder",
+ "title": "Reading",
+ "parentID": "home-pinned",
+ "childrenIds": [
+ "home-p1",
+ "home-p2"
+ ],
+ "isUnread": false,
+ "originatingDevice": "FIXTURE",
+ "createdAt": 800000000.0,
+ "data": {
+ "list": {}
+ }
+ },
+ "home-p1",
+ {
+ "id": "home-p1",
+ "title": null,
+ "parentID": "home-folder",
+ "childrenIds": [],
+ "isUnread": false,
+ "originatingDevice": "FIXTURE",
+ "createdAt": 800000000.0,
+ "data": {
+ "tab": {
+ "savedURL": "https://example.com/news",
+ "savedTitle": "News",
+ "savedMuteStatus": "allowAudio",
+ "timeLastActiveAt": 800000000.0
+ }
+ }
+ },
+ "home-p2",
+ {
+ "id": "home-p2",
+ "title": "My blog",
+ "parentID": "home-folder",
+ "childrenIds": [],
+ "isUnread": false,
+ "originatingDevice": "FIXTURE",
+ "createdAt": 800000000.0,
+ "data": {
+ "tab": {
+ "savedURL": "https://example.com/blog",
+ "savedTitle": "Blog",
+ "savedMuteStatus": "allowAudio",
+ "timeLastActiveAt": 800000000.0
+ }
+ }
+ },
+ "home-today",
+ {
+ "id": "home-today",
+ "title": null,
+ "parentID": null,
+ "childrenIds": [
+ "home-t1",
+ "home-t2",
+ "home-t3"
+ ],
+ "isUnread": false,
+ "originatingDevice": "FIXTURE",
+ "createdAt": 800000000.0,
+ "data": {
+ "itemContainer": {
+ "containerType": {
+ "spaceItems": {
+ "_0": "home"
+ }
+ }
+ }
+ }
+ },
+ "home-t1",
+ {
+ "id": "home-t1",
+ "title": null,
+ "parentID": "home-today",
+ "childrenIds": [],
+ "isUnread": false,
+ "originatingDevice": "FIXTURE",
+ "createdAt": 800000000.0,
+ "data": {
+ "tab": {
+ "savedURL": "https://example.com/today/1",
+ "savedTitle": "Today 1",
+ "savedMuteStatus": "allowAudio",
+ "timeLastActiveAt": 800000000.0
+ }
+ }
+ },
+ "home-t2",
+ {
+ "id": "home-t2",
+ "title": null,
+ "parentID": "home-today",
+ "childrenIds": [],
+ "isUnread": false,
+ "originatingDevice": "FIXTURE",
+ "createdAt": 800000000.0,
+ "data": {
+ "tab": {
+ "savedURL": "https://example.com/today/2",
+ "savedTitle": "Today 2",
+ "savedMuteStatus": "allowAudio",
+ "timeLastActiveAt": 800000000.0
+ }
+ }
+ },
+ "home-t3",
+ {
+ "id": "home-t3",
+ "title": null,
+ "parentID": "home-today",
+ "childrenIds": [],
+ "isUnread": false,
+ "originatingDevice": "FIXTURE",
+ "createdAt": 800000000.0,
+ "data": {
+ "tab": {
+ "savedURL": "https://example.com/today/3",
+ "savedTitle": "Today 3",
+ "savedMuteStatus": "allowAudio",
+ "timeLastActiveAt": 800000000.0
+ }
+ }
+ },
+ "work-pinned",
+ {
+ "id": "work-pinned",
+ "title": null,
+ "parentID": null,
+ "childrenIds": [],
+ "isUnread": false,
+ "originatingDevice": "FIXTURE",
+ "createdAt": 800000000.0,
+ "data": {
+ "itemContainer": {
+ "containerType": {
+ "spaceItems": {
+ "_0": "work"
+ }
+ }
+ }
+ }
+ },
+ "work-today",
+ {
+ "id": "work-today",
+ "title": null,
+ "parentID": null,
+ "childrenIds": [
+ "work-split"
+ ],
+ "isUnread": false,
+ "originatingDevice": "FIXTURE",
+ "createdAt": 800000000.0,
+ "data": {
+ "itemContainer": {
+ "containerType": {
+ "spaceItems": {
+ "_0": "work"
+ }
+ }
+ }
+ }
+ },
+ "work-split",
+ {
+ "id": "work-split",
+ "title": null,
+ "parentID": "work-today",
+ "childrenIds": [
+ "work-s1",
+ "work-s2"
+ ],
+ "isUnread": false,
+ "originatingDevice": "FIXTURE",
+ "createdAt": 800000000.0,
+ "data": {
+ "splitView": {}
+ }
+ },
+ "work-s1",
+ {
+ "id": "work-s1",
+ "title": null,
+ "parentID": "work-split",
+ "childrenIds": [],
+ "isUnread": false,
+ "originatingDevice": "FIXTURE",
+ "createdAt": 800000000.0,
+ "data": {
+ "tab": {
+ "savedURL": "https://example.com/docs",
+ "savedTitle": "Docs",
+ "savedMuteStatus": "allowAudio",
+ "timeLastActiveAt": 800000000.0
+ }
+ }
+ },
+ "work-s2",
+ {
+ "id": "work-s2",
+ "title": null,
+ "parentID": "work-split",
+ "childrenIds": [],
+ "isUnread": false,
+ "originatingDevice": "FIXTURE",
+ "createdAt": 800000000.0,
+ "data": {
+ "tab": {
+ "savedURL": "https://example.com/tracker",
+ "savedTitle": "Tracker",
+ "savedMuteStatus": "allowAudio",
+ "timeLastActiveAt": 800000000.0
+ }
+ }
+ }
+ ],
+ "topAppsContainerIDs": [
+ {
+ "default": true
+ },
+ "fav"
+ ]
+ }
+ ]
+ }
+}
\ No newline at end of file
diff --git a/Tests/Fixtures/Arc/StorableWindows.json b/Tests/Fixtures/Arc/StorableWindows.json
new file mode 100644
index 0000000..a8baa18
--- /dev/null
+++ b/Tests/Fixtures/Arc/StorableWindows.json
@@ -0,0 +1,5 @@
+{
+ "sidebarViewPreferences": {
+ "sidebarWidth": 280.0
+ }
+}
\ No newline at end of file
diff --git a/Tests/Fixtures/Chromium/Default/Bookmarks b/Tests/Fixtures/Chromium/Default/Bookmarks
new file mode 100644
index 0000000..b418313
--- /dev/null
+++ b/Tests/Fixtures/Chromium/Default/Bookmarks
@@ -0,0 +1,54 @@
+{
+ "version": 1,
+ "roots": {
+ "bookmark_bar": {
+ "type": "folder",
+ "name": "Bookmarks bar",
+ "children": [
+ {
+ "type": "url",
+ "name": "Docs",
+ "url": "https://example.com/docs",
+ "date_added": "13300000000000000"
+ },
+ {
+ "type": "folder",
+ "name": "Reading",
+ "children": [
+ {
+ "type": "url",
+ "name": "",
+ "url": "https://example.com/read"
+ }
+ ]
+ },
+ {
+ "type": "folder",
+ "name": "Empty",
+ "children": []
+ },
+ {
+ "type": "url",
+ "name": "Local",
+ "url": "file:///etc/hosts"
+ }
+ ]
+ },
+ "other": {
+ "type": "folder",
+ "name": "Other",
+ "children": [
+ {
+ "type": "url",
+ "name": "Other one",
+ "url": "https://example.com/other"
+ }
+ ]
+ },
+ "synced": {
+ "type": "folder",
+ "name": "Mobile",
+ "children": []
+ }
+ }
+}
\ No newline at end of file
diff --git a/Tests/Fixtures/Chromium/Default/Preferences b/Tests/Fixtures/Chromium/Default/Preferences
new file mode 100644
index 0000000..5973aa0
--- /dev/null
+++ b/Tests/Fixtures/Chromium/Default/Preferences
@@ -0,0 +1,18 @@
+{
+ "extensions": {
+ "settings": {
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": {
+ "location": 1,
+ "state": 1,
+ "path": "aaaa/1.0"
+ },
+ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb": {
+ "location": 4,
+ "disable_reasons": [
+ 1
+ ],
+ "path": "/nowhere"
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Tests/Fixtures/Chromium/Default/Sessions/Session_13300000000000000 b/Tests/Fixtures/Chromium/Default/Sessions/Session_13300000000000000
new file mode 100644
index 0000000..60e70c6
Binary files /dev/null and b/Tests/Fixtures/Chromium/Default/Sessions/Session_13300000000000000 differ
diff --git a/Tests/Fixtures/Chromium/README.md b/Tests/Fixtures/Chromium/README.md
new file mode 100644
index 0000000..b5fc2fd
--- /dev/null
+++ b/Tests/Fixtures/Chromium/README.md
@@ -0,0 +1,5 @@
+A made-up Chromium profile (Default/) in Chromium's own formats, for the importer tests and
+the parser fuzzer (scripts/test-store.sh, scripts/fuzz.sh): a version 3 SNSS session with a
+closed tab, a tab with two navigations and a chrome:// page; Bookmarks with a nested, an empty
+and a file: entry; Preferences with one extension on and one turned off. Every address is on
+example.com.
diff --git a/Tests/Fixtures/Extension/ID b/Tests/Fixtures/Extension/ID
new file mode 100644
index 0000000..0f38e0b
--- /dev/null
+++ b/Tests/Fixtures/Extension/ID
@@ -0,0 +1 @@
+jeackjeedkojbpbfclolioidbpgjnnjg
diff --git a/Tests/Fixtures/Extension/manifest.json b/Tests/Fixtures/Extension/manifest.json
new file mode 100644
index 0000000..10af2b6
--- /dev/null
+++ b/Tests/Fixtures/Extension/manifest.json
@@ -0,0 +1,9 @@
+{
+ "manifest_version": 3,
+ "name": "Cra Scenario Fixture",
+ "version": "1.0",
+ "description": "Made up for scripts/scenario.sh: a popup, an options page, nothing else.",
+ "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArrHe8/bGDOAVbyjlzsPuq0Nb8Vh6M3P9bsaB8yP4q92PGXq8TkxmPiPGET9gyUOHxUdbMSSNlS6qxkm89gueuIFNTmXLKARMRMlCc2QvF6v+FZJfVZuXBCHWbdSe0SGAlptOWLoS/HFJQLT4q0hEcOXOyr27+XNpL2zp0awUaGlvYEfmmlGxwKwfhovl2odDdWdbM4Coe9IxnzIj6BP/1PvBtwdLDC8Z79wTrRXh/fo+LG3wQmsZzgIqFtqua+90zEqNskZOnJ6+c4iuF7bnfwKudWCSQt9SWEHCc/y7sIK2e2Xo7CL6nqPjbrtvyntHlCbKhV0WQo+VdEAVwp6SqQIDAQAB",
+ "action": { "default_popup": "popup.html", "default_title": "Cra Scenario Fixture" },
+ "options_ui": { "page": "options.html", "open_in_tab": true }
+}
diff --git a/Tests/Fixtures/Extension/options.html b/Tests/Fixtures/Extension/options.html
new file mode 100644
index 0000000..58a77b9
--- /dev/null
+++ b/Tests/Fixtures/Extension/options.html
@@ -0,0 +1 @@
+<!doctype html><meta charset="utf-8"><title>Fixture options</title><body>Options</body>
diff --git a/Tests/Fixtures/Extension/popup.html b/Tests/Fixtures/Extension/popup.html
new file mode 100644
index 0000000..1c89790
--- /dev/null
+++ b/Tests/Fixtures/Extension/popup.html
@@ -0,0 +1 @@
+<!doctype html><meta charset="utf-8"><title>Fixture popup</title><body style="width:200px;height:120px">Popup</body>
diff --git a/Tests/Fixtures/Pages/page.html b/Tests/Fixtures/Pages/page.html
new file mode 100644
index 0000000..3a46203
--- /dev/null
+++ b/Tests/Fixtures/Pages/page.html
@@ -0,0 +1,14 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>Fixture page</title>
+<style>body { font: 15px -apple-system, sans-serif; margin: 40px; } .row { height: 24px; border-bottom: 1px solid #ddd; }</style>
+<h1>Fixture page</h1>
+<p>A local page for scripts/scenario.sh: no network, a little layout, an input to type into.</p>
+<input placeholder="Type here">
+<div id="rows"></div>
+<script>
+ const n = new URLSearchParams(location.search).get('n') || '0';
+ document.title = 'Fixture ' + n;
+ const rows = document.getElementById('rows');
+ for (let i = 0; i < 200; i++) { const d = document.createElement('div'); d.className = 'row'; d.textContent = 'Row ' + i; rows.appendChild(d); }
+</script>
diff --git a/Tests/FuzzTests.swift b/Tests/FuzzTests.swift
new file mode 100644
index 0000000..872e683
--- /dev/null
+++ b/Tests/FuzzTests.swift
@@ -0,0 +1,118 @@
+import Foundation
+
+/// Feeds the parsers of other browsers' files with mutated copies of the fixtures: Chromium's
+/// SNSS session, Bookmarks and Preferences, and Arc's StorableSidebar.json. Built with
+/// AddressSanitizer by scripts/fuzz.sh; a crash or an ASan report fails the run and leaves the
+/// input in $CRA_FUZZ_OUT/crash-input. Seeded, so a run repeats exactly (CRA_FUZZ_SEED).
+/// Xcode's toolchain has no libFuzzer on macOS; this is the coverage-blind kind, mutations of
+/// real files rather than random bytes, which is what reaches past the first format check.
+@main
+enum FuzzTests {
+ @MainActor
+ static func main() throws {
+ let env = ProcessInfo.processInfo.environment
+ let iterations = Int(env["CRA_FUZZ_ITERATIONS"] ?? "") ?? 20000
+ var rng = SplitMix(seed: UInt64(env["CRA_FUZZ_SEED"] ?? "") ?? 0xC4A)
+ let out = URL(fileURLWithPath: env["CRA_FUZZ_OUT"] ?? NSTemporaryDirectory(), isDirectory: true)
+ let fixtures = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures")
+ let work = FileManager.default.temporaryDirectory.appendingPathComponent("cra-fuzz-\(UUID().uuidString)", isDirectory: true)
+ let arc = work.appendingPathComponent("Arc", isDirectory: true), profile = work.appendingPathComponent("Default", isDirectory: true)
+ try FileManager.default.createDirectory(at: arc, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: profile, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: work) }
+ setenv("CRA_DATA_DIR", work.path, 1)
+ setenv("CRA_ARC_DIR", arc.path, 1)
+
+ let chromium = fixtures.appendingPathComponent("Chromium/Default")
+ let session = try Data(contentsOf: chromium.appendingPathComponent("Sessions/Session_13300000000000000"))
+ let targets: [(name: String, seed: Data, run: (Data) throws -> Void)] = [
+ ("SNSS session", session, { _ = ChromiumImporter.parseSession($0) }),
+ ("Bookmarks", try Data(contentsOf: chromium.appendingPathComponent("Bookmarks")), {
+ try $0.write(to: profile.appendingPathComponent("Bookmarks"))
+ _ = ChromiumImporter.bookmarks(profile: profile)
+ }),
+ ("Preferences", try Data(contentsOf: chromium.appendingPathComponent("Preferences")), {
+ try $0.write(to: profile.appendingPathComponent("Preferences"))
+ _ = ExtensionImporter.disabledIDs(inProfile: profile)
+ }),
+ ("StorableSidebar.json", try Data(contentsOf: fixtures.appendingPathComponent("Arc/StorableSidebar.json")), {
+ try $0.write(to: arc.appendingPathComponent("StorableSidebar.json"))
+ _ = try? ArcImporter.plan()
+ }),
+ ]
+ let current = out.appendingPathComponent("crash-input")
+ for (name, seed, run) in targets {
+ for _ in 0..<iterations / targets.count {
+ let input = mutate(seed, others: targets.map(\.seed), &rng)
+ // Written first: if the parser takes the process down, this is the reproducer.
+ try input.write(to: current)
+ try run(input)
+ }
+ print("fuzz: \(name): \(iterations / targets.count) inputs")
+ }
+ try? FileManager.default.removeItem(at: current)
+ print("Fuzz: no crash in \(iterations) inputs")
+ }
+
+ /// One to four byte-level edits, or a JSON-aware one for JSON seeds.
+ static func mutate(_ seed: Data, others: [Data], _ rng: inout SplitMix) -> Data {
+ if seed.first == UInt8(ascii: "{"), rng.next(4) == 0, let json = try? JSONSerialization.jsonObject(with: seed),
+ let data = try? JSONSerialization.data(withJSONObject: mutateJSON(json, &rng, depth: 0), options: [.fragmentsAllowed]) {
+ return data
+ }
+ var b = [UInt8](seed)
+ for _ in 0...rng.next(4) {
+ guard !b.isEmpty else { break }
+ let i = rng.next(b.count)
+ switch rng.next(7) {
+ case 0: b[i] ^= UInt8(1 << rng.next(8))
+ case 1: b[i] = [0, 0xFF, 0x7F, 0x80, 0x01, 0xFE][rng.next(6)]
+ case 2: b.removeSubrange(i..<min(b.count, i + 1 + rng.next(16)))
+ case 3: b.insert(contentsOf: (0..<1 + rng.next(8)).map { _ in UInt8(rng.next(256)) }, at: i)
+ case 4: b = Array(b.prefix(i))
+ case 5:
+ let j = rng.next(b.count), n = min(1 + rng.next(32), b.count - j)
+ b.insert(contentsOf: b[j..<(j + n)], at: i)
+ default:
+ let other = [UInt8](others[rng.next(others.count)])
+ if !other.isEmpty { let j = rng.next(other.count); b.insert(contentsOf: other[j..<min(other.count, j + 1 + rng.next(32))], at: i) }
+ }
+ }
+ // Lengths at the extremes: the parsers read sizes from the file itself.
+ if b.count >= 12, rng.next(3) == 0 {
+ let i = 8 + rng.next(b.count - 11)
+ for (k, v) in [0xFF, 0xFF, 0xFF, 0x7F].enumerated() where i + k < b.count { b[i + k] = UInt8(v) }
+ }
+ return Data(b)
+ }
+
+ static func mutateJSON(_ value: Any, _ rng: inout SplitMix, depth: Int) -> Any {
+ let replacements: [Any] = [NSNull(), 0, -1, Int.max, 1.5, "", "x", [Any](), [String: Any](), true]
+ if rng.next(6) == 0 || depth > 12 { return replacements[rng.next(replacements.count)] }
+ if var d = value as? [String: Any] {
+ for k in d.keys where rng.next(3) == 0 { d[k] = mutateJSON(d[k]!, &rng, depth: depth + 1) }
+ if rng.next(8) == 0, let k = d.keys.randomElement() { d[k] = nil }
+ return d
+ }
+ if var a = value as? [Any] {
+ for i in a.indices where rng.next(3) == 0 { a[i] = mutateJSON(a[i], &rng, depth: depth + 1) }
+ if rng.next(8) == 0, !a.isEmpty { a.swapAt(rng.next(a.count), rng.next(a.count)) }
+ if rng.next(10) == 0, !a.isEmpty { a.removeLast() }
+ return a
+ }
+ return value
+ }
+}
+
+/// SplitMix64: small, seedable, the same sequence on every Mac.
+struct SplitMix {
+ private var state: UInt64
+ init(seed: UInt64) { state = seed }
+ mutating func next(_ bound: Int) -> Int {
+ state &+= 0x9E37_79B9_7F4A_7C15
+ var z = state
+ z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
+ z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
+ return Int((z ^ (z >> 31)) % UInt64(max(bound, 1)))
+ }
+}
diff --git a/Tests/PolicyTests.swift b/Tests/PolicyTests.swift
new file mode 100644
index 0000000..9fc69af
--- /dev/null
+++ b/Tests/PolicyTests.swift
@@ -0,0 +1,106 @@
+import Foundation
+
+/// The decisions pulled out of the window controllers: the toolbar's buttons (Arc 1.170), what
+/// an extension click does, and the DevTools toggle. Table tests, no AppKit views.
+@main
+enum PolicyTests {
+ private static var checks = 0
+
+ @MainActor
+ static func main() {
+ toolbar()
+ extensionLaunch()
+ devToolsToggle()
+ featureFlags()
+ print("Policies: \(checks) checks passed")
+ }
+
+ private static func toolbar() {
+ typealias T = ToolbarComposition
+ func bar(_ kind: T.Kind, split: Bool = false, focused: Bool = true, back: Bool = false, forward: Bool = false,
+ loading: Bool = false, pinned: [String] = [], extensions: Bool = false) -> T {
+ T(kind: kind, inSplit: split, focusedPane: focused, canGoBack: back, canGoForward: forward, isLoading: loading,
+ pinnedExtensions: pinned, hasExtensions: extensions)
+ }
+ let full = bar(.normal, back: true, loading: true, pinned: ["a", "b"], extensions: true)
+ expect(full.left == [.toggleSidebar, .back(enabled: true), .forward(enabled: false), .reload(loading: true, enabled: true)],
+ "the full bar: toggle, ← → and ↻ (an ✕ while loading)")
+ expect(full.right == [.pinnedExtension("a"), .pinnedExtension("b"), .extensions, .addSplit],
+ "the right end: pinned extensions, Extensions, Split View")
+ expect(bar(.normal).right == [.addSplit], "no Extensions button without extensions")
+ let pane = bar(.normal, split: true, back: true, pinned: ["a"], extensions: true)
+ expect(pane.left == [.back(enabled: true), .forward(enabled: false)] && pane.right == [.splitOptions, .closePane],
+ "a focused split pane: only ← →, then its options and close")
+ expect(bar(.normal, split: true, focused: false).right == [.closePane], "an unfocused pane has only its close button")
+ expect(bar(.emptyPane, split: true).left == [.back(enabled: false), .forward(enabled: false)]
+ && bar(.emptyPane, split: true).right == [.closePane], "an empty pane: greyed ← → and close")
+ let noTab = bar(.noTab, pinned: ["a"], extensions: true)
+ expect(noTab.left == [.toggleSidebar, .back(enabled: false), .forward(enabled: false), .reload(loading: false, enabled: false)]
+ && noTab.right == [.pinnedExtension("a"), .extensions, .addSplit], "no tab: greyed navigation, the right end as usual")
+ let dev = bar(.developer, pinned: ["a"])
+ expect(dev.left == [.toggleSidebar] && dev.right == [.copyURL, .divider, .devTools, .pinnedExtension("a"), .addSplit],
+ "the developer bar: copy · divider · DevTools before the right end")
+ }
+
+ private static func extensionLaunch() {
+ typealias E = ExtensionLaunch.Extension
+ let popup = E(id: "pop", popupPath: "popup.html", optionsPath: "options.html")
+ let options = E(id: "opt", popupPath: nil, optionsPath: "settings.html")
+ let bare = E(id: "bare")
+ let off = E(id: "off", popupPath: "popup.html", enabled: false)
+ let all = [popup, options, bare, off]
+ expect(ExtensionLaunch.decide("pop", available: all, hasPage: true) == .runAction, "with a page, Chrome runs the action")
+ expect(ExtensionLaunch.decide("off", available: all, hasPage: true) == .nothing,
+ "a click never reaches an extension turned off in chrome://extensions")
+ expect(ExtensionLaunch.decide("off", available: all, hasPage: false) == .nothing, "not even without a page")
+ expect(ExtensionLaunch.fallback(off) == .nothing, "nor when Chrome's action failed")
+ expect(ExtensionLaunch.decide("gone", available: all, hasPage: true) == .nothing, "an extension of another profile does nothing")
+ expect(ExtensionLaunch.decide("pop", available: all, hasPage: false) == .popupWindow(url: "chrome-extension://pop/popup.html"),
+ "no page: the popup page in its own window")
+ expect(ExtensionLaunch.decide("opt", available: all, hasPage: false) == .openTab(url: "chrome-extension://opt/settings.html"),
+ "no popup: the options page in a tab")
+ expect(ExtensionLaunch.decide("bare", available: all, hasPage: false) == .openTab(url: "chrome://extensions/?id=bare"),
+ "neither: Chrome's details page for it")
+ }
+
+ private static func devToolsToggle() {
+ var t = DevToolsToggle()
+ expect(t.toggle() == .show && t.state == .opening, "closed: a press opens")
+ t.didOpen()
+ expect(t.toggle() == .close && t.state == .closing(reopen: false), "open: a press closes")
+ expect(t.toggle() == .none && t.state == .closing(reopen: true), "closing: a press is remembered, not sent")
+ expect(t.toggle() == .none && t.state == .closing(reopen: false), "a third press takes it back")
+ expect(t.didClose() == .none && t.state == .closed, "closed with nothing pending stays closed")
+ _ = t.toggle()
+ t.didOpen()
+ _ = t.toggle()
+ expect(t.show() == .none && t.state == .closing(reopen: true), "Inspect Element while closing waits for the close")
+ expect(t.didClose() == .show && t.state == .opening, "and opens them once closed")
+ t.didOpen()
+ expect(t.show() == .show && t.state == .open, "Inspect Element on open DevTools moves them to the element")
+ var external = DevToolsToggle()
+ external.didOpen()
+ expect(external.state == .open && external.toggle() == .close, "DevTools opened from Chromium's menu close on the next press")
+ var userClosed = DevToolsToggle()
+ _ = userClosed.toggle()
+ userClosed.didOpen()
+ expect(userClosed.didClose() == .none && userClosed.toggle() == .show, "closed from DevTools' own button: the next press opens")
+ }
+
+ private static func featureFlags() {
+ expect(FeatureFlags(parsing: "").backdrop == .layer, "the calibrated backdrop layer is the default")
+ expect(FeatureFlags(parsing: "backdrop=material").backdrop == .material, "CRA_FLAGS picks the material path")
+ expect(FeatureFlags(parsing: "x=1&backdrop=material&y").backdrop == .material, "other keys around it are ignored")
+ expect(FeatureFlags(parsing: "backdrop=glass").backdrop == .layer && FeatureFlags(parsing: "backdrop").backdrop == .layer,
+ "an unknown value or a bare key keeps the default")
+ expect(FeatureFlags(parsing: "backdrop=material").summary == "backdrop=material", "the log line names the path")
+ }
+
+ private static func expect(_ condition: @autoclosure () -> Bool, _ message: String) {
+ guard condition() else {
+ FileHandle.standardError.write(Data("FAIL: \(message)\n".utf8))
+ exit(1)
+ }
+ checks += 1
+ }
+}
diff --git a/Tests/Scenarios/component-snapshots.scenario b/Tests/Scenarios/component-snapshots.scenario
new file mode 100644
index 0000000..54010fe
--- /dev/null
+++ b/Tests/Scenarios/component-snapshots.scenario
@@ -0,0 +1,31 @@
+# Views whose geometry Cra takes from Arc, drawn from the running window and compared with
+# Tests/Snapshots/ (Cra's own drawing: no blur, no page content). Record a reference again
+# only after checking that view against Arc 1:1 (docs/testing.md).
+budget rss=600 stalls50=10 # turning developer mode on or off stalls 130–650 ms (a reload)
+port 47123
+cra://debug?windowSize=1280x800
+cra://import?source=arc&archive=0&settings=0
+wait 2
+cra://action/space2
+wait 2
+snapshot SpaceHeaderView space-header
+snapshot FavoritesGridView favorites-grid
+snapshot FolderRowView pinned-folder
+snapshot TabRowView today-tab-row
+snapshot NewTabRowView new-tab-row
+snapshot SpaceDockView space-dock
+cra://open?url=${PAGE}?n=snap
+wait 3
+snapshot SidebarURLPill url-pill
+cra://action/toggleToolbar
+wait 1
+snapshot PaneToolbarView toolbar
+cra://action/toggleDeveloperMode
+wait 2
+snapshot PaneToolbarView toolbar-developer
+cra://action/toggleDeveloperMode
+cra://action/addSplitView
+wait 3
+snapshot PaneToolbarView,0 toolbar-split-pane
+snapshot PaneToolbarView,1 toolbar-split-empty-pane
+snapshot SplitRowView split-row
diff --git a/Tests/Scenarios/dev-mode.scenario b/Tests/Scenarios/dev-mode.scenario
new file mode 100644
index 0000000..6038973
--- /dev/null
+++ b/Tests/Scenarios/dev-mode.scenario
@@ -0,0 +1,17 @@
+# Developer mode toggled on a site and DevTools opened and closed five times, then twice in
+# quick succession (the press made while DevTools close: DevToolsToggle).
+budget rss=600 stalls50=5
+cra://open?url=${PAGE}?n=dev
+wait 3
+cra://action/toggleDeveloperMode
+wait 2
+pace 2
+repeat 10 cra://action/devTools
+pace 0.1
+cra://action/devTools
+cra://action/devTools
+cra://action/devTools
+wait 3
+pace 0.2
+cra://action/toggleDeveloperMode
+wait 2
diff --git a/Tests/Scenarios/extension-lifecycle.scenario b/Tests/Scenarios/extension-lifecycle.scenario
new file mode 100644
index 0000000..e9851b5
--- /dev/null
+++ b/Tests/Scenarios/extension-lifecycle.scenario
@@ -0,0 +1,25 @@
+# An unpacked extension installed, used, turned off in chrome://extensions, clicked while off,
+# turned on and removed. A click must never reach a disabled extension (GitHub #41).
+budget rss=600 stalls50=5
+cra://debug?installExtension=${FIXTURES}/Extension
+relaunch
+cra://open?url=${PAGE}?n=ext
+wait 3
+cra://debug?extensionAction=${EXTENSION_ID}
+wait 2
+cra://dismiss
+cra://open?url=chrome://extensions/?id=${EXTENSION_ID}
+wait 3
+cra://debug?pageJS=chrome.management.setEnabled('${EXTENSION_ID}',false)
+expect-log extension ${EXTENSION_ID} turned off in Default
+cra://debug?extensionAction=${EXTENSION_ID}
+wait 2
+cra://debug?pageJS=chrome.management.setEnabled('${EXTENSION_ID}',true)
+expect-log extension ${EXTENSION_ID} turned on in Default
+cra://debug?extensionAction=${EXTENSION_ID}
+wait 2
+cra://dismiss
+cra://debug?removeExtension=${EXTENSION_ID}
+relaunch
+cra://debug?extensionAction=${EXTENSION_ID}
+wait 2
diff --git a/Tests/Scenarios/fifty-tabs.scenario b/Tests/Scenarios/fifty-tabs.scenario
new file mode 100644
index 0000000..82e0350
--- /dev/null
+++ b/Tests/Scenarios/fifty-tabs.scenario
@@ -0,0 +1,14 @@
+# Fifty pages opened, switched through and closed: leaks, helper processes never reaped,
+# and the layout cost of a long Today list.
+budget rss=900 stalls50=90 # each new tab stalls ~100 ms today (Nov 2026)
+cra://open?url=${PAGE}?n=first
+wait 3
+helpers baseline
+pace 0.3
+repeat 50 cra://open?url=${PAGE}?n=${i}
+wait 5
+pace 0.15
+repeat 50 cra://action/nextTab
+repeat 50 cra://action/closeTab # the first page stays
+wait 3
+helpers settle 2
diff --git a/Tests/Scenarios/fullscreen.scenario b/Tests/Scenarios/fullscreen.scenario
new file mode 100644
index 0000000..82aea64
--- /dev/null
+++ b/Tests/Scenarios/fullscreen.scenario
@@ -0,0 +1,18 @@
+# Fullscreen, an extension popup and its options page over it, and back: window and Space
+# transitions. It takes over a Space, so it runs only with CRA_SCENARIO_SCREEN=1 (CI).
+requires screen
+budget rss=600 stalls50=5
+cra://debug?installExtension=${FIXTURES}/Extension
+relaunch
+cra://open?url=${PAGE}?n=full
+wait 3
+cra://debug?fullscreen=1
+wait 3
+cra://debug?extensionAction=${EXTENSION_ID}
+wait 2
+cra://dismiss
+cra://open?url=chrome-extension://${EXTENSION_ID}/options.html
+wait 3
+cra://action/closeTab
+cra://debug?fullscreen=0
+wait 3
diff --git a/Tests/Scenarios/onboarding-import.scenario b/Tests/Scenarios/onboarding-import.scenario
new file mode 100644
index 0000000..137c9cc
--- /dev/null
+++ b/Tests/Scenarios/onboarding-import.scenario
@@ -0,0 +1,8 @@
+# A new Mac: onboarding up, a headless Arc import of the made-up profile (CRA_ARC_DIR =
+# Tests/Fixtures/Arc), then two minutes idle, where the crashes after a long import showed up.
+fresh
+budget rss=500 stalls50=5
+wait 3
+cra://import?source=arc&archive=1&settings=1
+expect-log imported 2 spaces, [0-9]+ tabs, [0-9]+ folders, 2 archived
+wait 120
diff --git a/Tests/Scenarios/sleep-tabs.scenario b/Tests/Scenarios/sleep-tabs.scenario
new file mode 100644
index 0000000..1aba4c0
--- /dev/null
+++ b/Tests/Scenarios/sleep-tabs.scenario
@@ -0,0 +1,14 @@
+# Thirty background pages put to sleep: the timed pass no unit test reaches with a real page,
+# run here with a one-second threshold (cra://debug?sleepTabs) instead of waiting an hour.
+budget rss=800 stalls50=70 # each new tab stalls ~100 ms today (Nov 2026)
+cra://open?url=${PAGE}?n=first
+wait 3
+helpers baseline
+pace 0.3
+repeat 30 cra://open?url=${PAGE}?n=${i}
+cra://action/nextTab
+wait 4
+cra://debug?sleepTabs=1
+wait 4
+expect-log tab sleep unloads
+helpers settle 2
diff --git a/Tests/Snapshots/favorites-grid.png b/Tests/Snapshots/favorites-grid.png
new file mode 100644
index 0000000..a2a40a3
Binary files /dev/null and b/Tests/Snapshots/favorites-grid.png differ
diff --git a/Tests/Snapshots/new-tab-row.png b/Tests/Snapshots/new-tab-row.png
new file mode 100644
index 0000000..6b5e27c
Binary files /dev/null and b/Tests/Snapshots/new-tab-row.png differ
diff --git a/Tests/Snapshots/pinned-folder.png b/Tests/Snapshots/pinned-folder.png
new file mode 100644
index 0000000..f62b199
Binary files /dev/null and b/Tests/Snapshots/pinned-folder.png differ
diff --git a/Tests/Snapshots/space-dock.png b/Tests/Snapshots/space-dock.png
new file mode 100644
index 0000000..470dae6
Binary files /dev/null and b/Tests/Snapshots/space-dock.png differ
diff --git a/Tests/Snapshots/space-header.png b/Tests/Snapshots/space-header.png
new file mode 100644
index 0000000..3bb7e6c
Binary files /dev/null and b/Tests/Snapshots/space-header.png differ
diff --git a/Tests/Snapshots/split-row.png b/Tests/Snapshots/split-row.png
new file mode 100644
index 0000000..28f82a9
Binary files /dev/null and b/Tests/Snapshots/split-row.png differ
diff --git a/Tests/Snapshots/today-tab-row.png b/Tests/Snapshots/today-tab-row.png
new file mode 100644
index 0000000..81f8623
Binary files /dev/null and b/Tests/Snapshots/today-tab-row.png differ
diff --git a/Tests/Snapshots/toolbar-developer.png b/Tests/Snapshots/toolbar-developer.png
new file mode 100644
index 0000000..ce0ca5e
Binary files /dev/null and b/Tests/Snapshots/toolbar-developer.png differ
diff --git a/Tests/Snapshots/toolbar-split-empty-pane.png b/Tests/Snapshots/toolbar-split-empty-pane.png
new file mode 100644
index 0000000..91d35ba
Binary files /dev/null and b/Tests/Snapshots/toolbar-split-empty-pane.png differ
diff --git a/Tests/Snapshots/toolbar-split-pane.png b/Tests/Snapshots/toolbar-split-pane.png
new file mode 100644
index 0000000..12e4c7c
Binary files /dev/null and b/Tests/Snapshots/toolbar-split-pane.png differ
diff --git a/Tests/Snapshots/toolbar.png b/Tests/Snapshots/toolbar.png
new file mode 100644
index 0000000..2371d92
Binary files /dev/null and b/Tests/Snapshots/toolbar.png differ
diff --git a/Tests/Snapshots/url-pill.png b/Tests/Snapshots/url-pill.png
new file mode 100644
index 0000000..0aeee21
Binary files /dev/null and b/Tests/Snapshots/url-pill.png differ
diff --git a/Tests/StoreTests.swift b/Tests/StoreTests.swift
new file mode 100644
index 0000000..8a695f5
--- /dev/null
+++ b/Tests/StoreTests.swift
@@ -0,0 +1,214 @@
+import Foundation
+
+/// 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
+/// import run in milliseconds, against a made-up Arc profile (Tests/Fixtures/Arc).
+@main
+enum StoreTests {
+ private static var checks = 0
+
+ @MainActor
+ static func main() throws {
+ let data = FileManager.default.temporaryDirectory.appendingPathComponent("cra-store-tests-\(UUID().uuidString)", isDirectory: true)
+ defer { try? FileManager.default.removeItem(at: data) }
+ // Before AppPaths and ArcImporter read them: they are fixed for the process.
+ setenv("CRA_DATA_DIR", data.path, 1)
+ setenv("CRA_ARC_DIR", URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/Arc").path, 1)
+
+ try arcImport()
+ chromiumProfile()
+ autoArchive()
+ tabSleepCadence()
+ integrity()
+ liveFolderExpiry()
+ stampsUseTheClock()
+ persistenceFaults()
+ print("Store: \(checks) checks passed")
+ }
+
+ @MainActor
+ private static func arcImport() throws {
+ let plan = try ArcImporter.plan()
+ expect(plan.spaces.map(\.title) == ["Home", "Work"], "both spaces come over in Arc's order")
+ expect(plan.spaces.map(\.emoji) == ["🏠", "💼"], "emoji_v2 and the older numeric emoji both read")
+ let home = plan.spaces[0], work = plan.spaces[1]
+ expect(home.favorites.compactMap(\.url) == ["https://example.com/mail", "https://example.com/calendar"],
+ "the profile's top apps become the space's favorites")
+ expect(home.pinned.count == 1 && home.pinned[0].isFolder && home.pinned[0].customTitle == "Reading"
+ && home.pinned[0].children.count == 2, "a pinned folder keeps its title and tabs")
+ expect(home.pinned[0].children[1].customTitle == "My blog", "a renamed tab keeps its custom title")
+ expect(home.today.count == 3, "Today tabs come over")
+ expect(work.pinned.isEmpty && work.today.count == 1 && work.today[0].isFolder && work.today[0].children.count == 2,
+ "a split view is flattened into a folder of its tabs")
+ expect(plan.archive.map(\.pageTitle) == ["Old two", "Old one"], "archived tabs are newest first")
+ expect(plan.archive.map(\.reason) == [.manual, .auto] && plan.archive.map(\.spaceTitle) == ["Work", "Home"],
+ "archive entries keep their reason and space")
+ expect(plan.settings.sidebarWidth == 280, "the sidebar width comes from StorableWindows.json")
+
+ let composition = AppComposition(clock: ManualScheduler())
+ let result = composition.store.apply(plan, includeArchive: true, includeSettings: true)
+ expect(result.spaces == 2 && result.archived == 2, "applying the plan adds both spaces and the archive")
+ 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")
+ }
+
+ /// Chrome-family profiles (Tests/Fixtures/Chromium/Default): the last session's open tabs,
+ /// bookmarks and which extensions are turned off.
+ private static func chromiumProfile() {
+ let profile = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/Chromium/Default")
+ let tabs = ChromiumImporter.openTabs(profile: profile)
+ expect(tabs.map(\.url) == ["https://example.com/one", "https://example.com/two-b"],
+ "open tabs: the selected navigation of each, closed tabs and chrome:// pages left out, in window order")
+ expect(tabs.map(\.pageTitle) == ["One", "Two, then Ü"], "titles come from the session's UTF-16 strings")
+ let marks = ChromiumImporter.bookmarks(profile: profile)
+ expect(marks.bar.map(\.pageTitle) == ["Docs", "Reading"] && marks.bar[1].children.map(\.url) == ["https://example.com/read"],
+ "the bookmarks bar keeps folders with web pages, drops empty folders and file: links")
+ expect(marks.other.map(\.url) == ["https://example.com/other"], "other and mobile bookmarks come after")
+ expect(ChromiumImporter.parseSession(Data("SNSS".utf8) + Data([4, 0, 0, 0]) + Data(repeating: 1, count: 16)).isEmpty,
+ "an encrypted session (version 4) gives nothing rather than garbage")
+ expect(ExtensionImporter.disabledIDs(inProfile: profile) == ["bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"],
+ "an extension with disable_reasons is off, one in state 1 is on")
+ }
+
+ /// Arc archives unused Today tabs on a 30-minute pass; the selected tab stays.
+ @MainActor
+ private static func autoArchive() {
+ let clock = ManualScheduler()
+ let composition = AppComposition(clock: clock)
+ let store = composition.store
+ store.settings.autoArchiveEnabled = true
+ store.settings.autoArchive = .twelveHours
+ let idle = store.createTab(url: "https://example.com/idle", select: false)
+ let shown = store.createTab(url: "https://example.com/shown", select: true)
+ composition.startPeriodicWork {}
+ func archived(_ id: UUID) -> Bool { store.item(id) == nil }
+ clock.advance(by: 12 * 3600 - 1)
+ expect(!archived(idle.id), "a tab is kept until it has been unused for the whole threshold")
+ // The model stamps createdAt from the real clock, a moment after this one started:
+ // the pass at exactly 12 h still sees the tab as fresh, the one after archives it.
+ clock.advance(by: AppComposition.autoArchiveInterval + 1)
+ expect(archived(idle.id), "the next pass after the threshold archives it")
+ expect(!archived(shown.id), "the selected tab is never archived")
+ store.settings.autoArchiveEnabled = false
+ let later = store.createTab(url: "https://example.com/later", select: false)
+ clock.advance(by: 48 * 3600)
+ expect(!archived(later.id), "with auto-archive off nothing is archived")
+ }
+
+ /// Tab sleeping asks the windows once a minute, and only while it is turned on.
+ @MainActor
+ private static func tabSleepCadence() {
+ let clock = ManualScheduler()
+ let composition = AppComposition(clock: clock)
+ composition.store.settings.tabSleepEnabled = true
+ var passes = 0
+ composition.startPeriodicWork { passes += 1 }
+ clock.advance(by: 59)
+ expect(passes == 0, "no pass before the first minute")
+ clock.advance(by: 1)
+ expect(passes == 1, "a pass every minute")
+ clock.advance(by: 9 * 60)
+ expect(passes == 10, "ten passes in ten minutes")
+ composition.store.settings.tabSleepEnabled = false
+ clock.advance(by: 10 * 60)
+ expect(passes == 10, "no passes while tab sleeping is off")
+ composition.startPeriodicWork { passes += 100 }
+ expect(clock.pendingCount == 2, "starting again replaces the timers instead of adding to them")
+ }
+
+ /// The integrity check stays quiet through ordinary changes and names a broken link.
+ @MainActor
+ private static func integrity() {
+ let store = AppComposition(clock: ManualScheduler()).store
+ expect(store.integrityProblems().isEmpty, "a fresh sidebar is sound")
+ let a = store.createTab(url: "https://example.com/a")
+ let b = store.createTab(url: "https://example.com/b", pinned: true)
+ store.createTab(url: "https://example.com/c", select: false)
+ store.archiveTab(a.id, reason: .manual)
+ store.reopenLastArchived()
+ expect(store.integrityProblems().isEmpty, "creating, pinning, archiving and reopening keep it sound")
+ var parent = store.item(b.parentID!)!
+ parent.children.removeAll { $0 == b.id }
+ store.items[parent.id] = parent
+ let problems = store.integrityProblems()
+ expect(problems.count == 1 && problems[0].contains("not listed by its parent"), "a tab its parent lost is reported")
+ parent.children.append(b.id)
+ store.items[parent.id] = parent
+ let today = store.focusedSpace.todayContainerID
+ var other = store.item(today)!
+ other.children.append(b.id)
+ store.items[today] = other
+ expect(store.integrityProblems().contains { $0.contains("listed by both") }, "a tab listed by two parents is reported")
+ other.children.removeLast()
+ store.items[today] = other
+ let second = store.createSpace(title: "Second", emoji: "2", focus: false)
+ store.prefs.windows[0].selectedTabPerSpace[second.id] = b.id
+ expect(store.integrityProblems().contains { $0.contains("lives elsewhere") }, "a window selecting another space's tab is reported")
+ }
+
+ /// A pull request that left the results stays for the grace period, then goes, all on the clock.
+ @MainActor
+ private static func liveFolderExpiry() {
+ let clock = ManualScheduler()
+ let store = AppComposition(clock: clock).store
+ guard let folder = store.createLiveFolder(.github, inSpace: store.focusedSpaceID) else { return expect(false, "a live folder is made") }
+ let one = LivePullRequest(owner: "cra", repo: "cra", number: 1, title: "One")
+ let two = LivePullRequest(owner: "cra", repo: "cra", number: 2, title: "Two")
+ store.applyLiveResults([one, two], to: folder.id, ssoOrganizations: [])
+ expect(store.item(folder.id)?.liveFolder?.lastFetch == clock.now && store.children(of: folder.id).count == 2,
+ "a refresh fills the folder and stamps the fetch with the clock")
+ clock.advance(by: 600)
+ store.applyLiveResults([one], to: folder.id, ssoOrganizations: [])
+ let gone = store.children(of: folder.id).first { $0.tab?.liveItemURL == two.url }
+ expect(gone?.tab?.liveGoneAt == clock.now, "a pull request that left the results is marked gone now")
+ clock.advance(by: 3599)
+ store.expireLiveItems(olderThan: 3600)
+ expect(store.children(of: folder.id).count == 2, "it stays through the grace period")
+ clock.advance(by: 1)
+ store.expireLiveItems(olderThan: 3600)
+ expect(store.children(of: folder.id).map(\.tab?.liveItemURL) == [one.url], "and goes when it ends")
+ expect(store.integrityProblems().isEmpty, "live folder changes keep the sidebar sound")
+ }
+
+ /// Every date the store writes comes from its clock.
+ @MainActor
+ private static func stampsUseTheClock() {
+ let clock = ManualScheduler()
+ let store = AppComposition(clock: clock).store
+ clock.advance(by: 86400)
+ let a = store.createTab(url: "https://example.com/a"), b = store.createTab(url: "https://example.com/b")
+ expect(store.item(b.id)?.tab?.timeLastActiveAt == clock.now, "selecting a tab stamps it with the clock")
+ let split = store.createSplit(with: [a.id, b.id])
+ expect(split?.split?.timeLastActiveAt == clock.now, "a new split is stamped with the clock")
+ store.recordVisit(url: "https://example.com/a", title: "A")
+ expect(store.history["https://example.com/a"]?.lastVisit == clock.now, "history visits use the clock")
+ store.archiveLittleWindowPage(url: "https://example.com/little", title: "Little")
+ expect(store.archive.first?.archivedAt == clock.now, "a Little Window's page is archived at the clock's time")
+ let incognito = store.addIncognitoWindow(frame: nil)
+ expect(incognito.focusedSpaceID.flatMap { store.spaces[$0] }?.createdAt == clock.now, "an incognito space is made at the clock's time")
+ expect(store.integrityProblems().isEmpty, "and the sidebar stays sound")
+ }
+
+ /// A file that can't be read or written says so (a fault) instead of failing silently.
+ private static func persistenceFaults() {
+ let before = CraLog.faultCount
+ try? Data("{ not json".utf8).write(to: AppPaths.file("broken.json"))
+ let loaded = JSONStore<[String]>("broken.json").load(or: { ["fallback"] })
+ expect(loaded == ["fallback"] && FileManager.default.fileExists(atPath: AppPaths.file("broken.json.corrupt").path),
+ "a corrupt file is set aside and the fallback used")
+ expect(CraLog.faultCount == before + 1, "and the log has a fault for it")
+ JSONStore<[Double]>("nan.json").saveNow([.nan])
+ expect(CraLog.faultCount == before + 2, "a value JSON can't hold is a fault, not a silent skip")
+ JSONStore<[String]>("missing-folder/x.json").saveNow(["x"])
+ expect(CraLog.faultCount == before + 3, "a write that fails is a fault")
+ }
+
+ private static func expect(_ condition: @autoclosure () -> Bool, _ message: String) {
+ guard condition() else {
+ FileHandle.standardError.write(Data("FAIL: \(message)\n".utf8))
+ exit(1)
+ }
+ checks += 1
+ }
+}
diff --git a/Tests/Support/ManualScheduler.swift b/Tests/Support/ManualScheduler.swift
new file mode 100644
index 0000000..41f52a3
--- /dev/null
+++ b/Tests/Support/ManualScheduler.swift
@@ -0,0 +1,50 @@
+import Foundation
+
+/// A clock that moves only when the test says so. `advance(by:)` runs every timer that falls
+/// due on the way, in time order, with `now` set to the moment each one fires.
+@MainActor
+final class ManualScheduler: Scheduler {
+ private struct Entry {
+ let id: Int
+ var due: Date
+ let interval: TimeInterval?
+ let handle: ScheduledWork
+ let work: @MainActor () -> Void
+ }
+
+ private(set) var now: Date
+ private var entries: [Entry] = []
+ private var nextID = 0
+
+ /// Starts at the real time: model factories (SidebarItem.tab) stamp createdAt with it.
+ init(now: Date = Date()) { self.now = now }
+
+ var pendingCount: Int { entries.filter { !$0.handle.isCancelled }.count }
+
+ func after(_ delay: TimeInterval, _ work: @escaping @MainActor () -> Void) -> ScheduledWork {
+ add(delay, repeats: false, work)
+ }
+
+ func every(_ interval: TimeInterval, _ work: @escaping @MainActor () -> Void) -> ScheduledWork {
+ add(interval, repeats: true, work)
+ }
+
+ private func add(_ interval: TimeInterval, repeats: Bool, _ work: @escaping @MainActor () -> Void) -> ScheduledWork {
+ nextID += 1
+ let id = nextID
+ let handle = ScheduledWork { [weak self] in self?.entries.removeAll { $0.id == id } }
+ entries.append(Entry(id: id, due: now.addingTimeInterval(interval), interval: repeats ? interval : nil, handle: handle, work: work))
+ return handle
+ }
+
+ func advance(by seconds: TimeInterval) {
+ let end = now.addingTimeInterval(seconds)
+ while let i = entries.indices.filter({ entries[$0].due <= end }).min(by: { (entries[$0].due, entries[$0].id) < (entries[$1].due, entries[$1].id) }) {
+ let entry = entries[i]
+ now = entry.due
+ if let interval = entry.interval { entries[i].due = entry.due.addingTimeInterval(interval) } else { entries.remove(at: i) }
+ entry.work()
+ }
+ now = end
+ }
+}
diff --git a/Tests/lint-baseline.txt b/Tests/lint-baseline.txt
new file mode 100644
index 0000000..0940d0c
--- /dev/null
+++ b/Tests/lint-baseline.txt
@@ -0,0 +1,22 @@
+# scripts/lint.py findings in code older than the rule. Only ever lower these.
+importer-without-fixture Services/Import/FirefoxImporter.swift:Firefox 1
+importer-without-fixture Services/Import/Importers.swift:Dia 1
+importer-without-fixture Services/Import/SafariImporter.swift:Safari 1
+importer-without-fixture Services/Import/ZenImporter.swift:Zen 1
+raw-observation-tracking UI/CommandBar/CommandBarView.swift 1
+raw-observation-tracking UI/Overlays.swift 3
+raw-observation-tracking UI/PaneToolbarView.swift 1
+raw-observation-tracking UI/Sidebar/DownloadsTray.swift 1
+raw-observation-tracking UI/Sidebar/LibraryView.swift 1
+raw-observation-tracking UI/Sidebar/List/SidebarView.swift 4
+raw-observation-tracking UI/Sidebar/List/SpaceColumnView.swift 2
+raw-observation-tracking UI/Sidebar/List/SpaceListView.swift 1
+raw-observation-tracking UI/Sidebar/List/SpacePagerView.swift 1
+raw-observation-tracking UI/Sidebar/NowPlayingTray.swift 1
+raw-observation-tracking UI/Sidebar/SpacesManagerView.swift 2
+raw-observation-tracking UI/SiteControlCenter.swift 1
+raw-observation-tracking UI/TabSwitcher/TabSwitcherView.swift 1
+raw-observation-tracking UI/Theme.swift 2
+raw-observation-tracking UI/Updates/UpdateBanner.swift 1
+raw-observation-tracking UI/Windows/LittleWindowController.swift 2
+raw-observation-tracking UI/Windows/MainWindowController.swift 2
diff --git a/Tests/test-browser-manager.sh b/Tests/test-browser-manager.sh
index dfa4522..de0fa14 100755
--- a/Tests/test-browser-manager.sh
+++ b/Tests/test-browser-manager.sh
@@ -8,8 +8,9 @@ trap 'rm -rf "$TEST_DIR"' EXIT
xcrun swiftc -swift-version 5 -emit-module -emit-library -module-name CraCEF \
Tests/BrowserManagerSupport/CraCEF.swift -o "$TEST_DIR/libCraCEF.dylib" \
-emit-module-path "$TEST_DIR/CraCEF.swiftmodule"
-xcrun swiftc -swift-version 5 -parse-as-library -I "$TEST_DIR" -L "$TEST_DIR" -lCraCEF \
+xcrun swiftc -swift-version 5 -parse-as-library ${CRA_TEST_SWIFTC_FLAGS:-} -I "$TEST_DIR" -L "$TEST_DIR" -lCraCEF \
-Xlinker -rpath -Xlinker "$TEST_DIR" \
- "$MANAGER_SOURCE" Sources/Cra/Services/NowPlaying.swift Sources/Cra/Services/PageScript.swift Tests/BrowserManagerSupport/AppServices.swift \
+ "$MANAGER_SOURCE" Sources/Cra/Services/NowPlaying.swift Sources/Cra/Services/PageScript.swift Sources/Cra/Services/Scheduler.swift Sources/Cra/Services/DevToolsToggle.swift Sources/Cra/Services/CraLog.swift Sources/Cra/Services/PageProbe.swift Sources/Cra/Services/Persistence.swift Tests/Support/ManualScheduler.swift Tests/BrowserManagerSupport/AppServices.swift \
Tests/BrowserManagerLifecycleTests.swift -o "$TEST_DIR/lifecycle-tests"
"$TEST_DIR/lifecycle-tests"
+[ -z "${CRA_TEST_KEEP:-}" ] || cp "$TEST_DIR/lifecycle-tests" "$CRA_TEST_KEEP/"
diff --git a/docs/development.md b/docs/development.md
index 06dee24..82fa618 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -55,6 +55,12 @@ the save panel.
scripts/test.sh # everything below except the smoke test, in seconds
scripts/test.sh core # only Packages/CraCore
Tests/smoke-launch.sh # launches build/Cra.app three times, about 30 s
+ scripts/scenario.sh all # user journeys in build/Cra.app, about 6 minutes
+ scripts/coverage.py # line coverage, and the changed-lines gate
+ scripts/fuzz.sh # mutated importer fixtures under AddressSanitizer
+ scripts/mutate.py # mutation testing of the pure code, minutes
+
+[testing.md](testing.md) has the rules, the layers, the gates and how to write a scenario.
CI runs `scripts/test.sh` on every pull request (no CEF download) and the smoke test on the
app it builds.
@@ -69,6 +75,11 @@ app it builds.
few production files with `swiftc` against fakes (`Tests/BrowserManagerSupport` stands in
for CraCEF and the rest of the app). When the manager calls something new from the app, add
a stub to `AppServices.swift`.
+- `scripts/test-store.sh`: the real `SidebarStore`, `AppComposition` and importers on a
+ `ManualScheduler`, against the made-up Arc and Chromium profiles in `Tests/Fixtures`.
+- `scripts/test-policies.sh`: the decisions pulled out of the window controllers
+ (`ToolbarComposition`, `ExtensionLaunch`, `DevToolsToggle`, `FeatureFlags`).
+- `scripts/lint.py`: Cra's own rules (testing.md), checked by `scripts/test.sh`.
- `Tests/smoke-launch.sh [app]`: starts the app on a throwaway data folder with no pages,
with a page opened, then with it restored, and quits it like ⌘Q after a settings write.
It fails on a crash, a hang, an error exit or a new crash report, which is how a `CHECK`
@@ -77,6 +88,11 @@ app it builds.
What none of these see: compositing (the sidebar blur), fullscreen spaces, and how real sites
behave. Check those by hand, and say how in the PR.
+Scenario hooks for a command file (`cra://debug?…`): `checkStore=1` logs a fault per broken
+sidebar link, `pageJS=<js>` runs script in the focused page, `installExtension=<folder>` and
+`removeExtension=<id>`, `extensionAction=<id>`, `fullscreen=1|0`, `windowSize=1280x800`,
+`snapshot=<ViewClass[,n]>&out=<png>`, `sleepTabs=<seconds>`, `relaunch=1` and `quit=1`.
+
## Running a test instance
`scripts/dev.sh` builds a separate `CraDev.app`, including Sparkle, without a production
diff --git a/docs/testing.md b/docs/testing.md
new file mode 100644
index 0000000..3c17537
--- /dev/null
+++ b/docs/testing.md
@@ -0,0 +1,120 @@
+# Testing
+
+How Cra is tested, what runs when, and the numbers that gate a change (GitHub #44, #45).
+Commands for each piece are in [development.md](development.md#tests).
+
+## Rules
+
+1. **Test the decision, not the doing.** What decides (which tab to select, whether a tab
+ may sleep, which buttons a toolbar has) is a value type with a table test. What performs
+ it (an `NSView`, a CEF call) gets no unit test; scenarios cover it.
+2. **Only test at seams that exist in production.** When logic can only be reached by building
+ a window, move the logic (`ToolbarComposition`, `ExtensionLaunch`, `DevToolsToggle`);
+ don't add a test hook to the window.
+3. **No sleeps, no wall clock.** Decisions taken from time use the app's clock
+ (`Scheduler`, injected through `AppComposition`); a test passes a `ManualScheduler` and
+ advances it, so the 30-minute archive pass runs in a millisecond.
+4. **Fixtures over dictionaries.** Every format Cra reads from another browser has a made-up
+ profile in that browser's own format under `Tests/Fixtures/<Browser>` (no real browsing
+ data). Parsers are tested on those files, and the fuzzer mutates them.
+5. **A bug fix comes with the test that would have caught it.**
+6. **Never assert on a fake's bookkeeping alone.** A test whose only check is "the fake
+ recorded a call" tests the fake.
+7. **A flaky test is rewritten on the clock or deleted**, never retried or given a sleep.
+
+## Layers
+
+| Layer | What | Where | Runs |
+|---|---|---|---|
+| L0 static | `scripts/lint.py`: the bug classes below as rules | `scripts/test.sh` | every PR |
+| L1 unit | `Packages/CraCore`: pure types, `swift test` | `scripts/test.sh` | every PR |
+| L2 contract | production files compiled against fakes: browser manager, store and importers on a manual clock, policies | `scripts/test-*.sh` | every PR |
+| L3 component | Arc-specified views drawn from the running app and compared with `Tests/Snapshots` | `component-snapshots` scenario | nightly |
+| L4 scenario | the real app driven through a journey, invariants only | `scripts/scenario.sh` | one per PR, all nightly |
+| L5 human | the sidebar blur, fullscreen Spaces, GPU, real sites | the PR description | each PR, release |
+
+L0–L2 need no CEF and finish in about 20 seconds. L3 lives in the running app because Cra's
+views can't be compiled without most of the app; it draws each view's layer tree (no blur,
+no page content), so it checks geometry, ink and fills.
+
+## Gates and budgets
+
+- **Changed lines under test ≥ 70 %** (`scripts/coverage.py`, posted on the PR). Of the lines a
+ PR adds or changes in files a harness compiles, at least 70 % must run. Changed files no
+ harness compiles (views, CEF glue) are listed, not counted.
+- **CraCore ≥ 85 % of lines.** There is no target for the whole repo: one would be met by
+ testing the easy files.
+- **Mutation score ≥ 70 %** (`scripts/mutate.py`, weekly): one operator flipped at a time in
+ the pure code must fail a test.
+- **Scenario invariants**, the same for every scenario: the app is still running at the end,
+ no new crash report for its processes, no `fault:` line in `cra.log`, the sidebar sound
+ (`SidebarIntegrity`), main-thread stalls inside the scenario's budget, Cra's memory inside
+ its budget, helper processes back to baseline five seconds after tabs close, and a quit
+ within 20 seconds.
+
+Stall budgets are set from what the app does today, so they catch regressions rather than
+describe a goal. The count of stalls over 50 ms is steady from run to run and carries the
+budget; the longest stall swings with machine load (235 ms one run, 498 ms the next), so it
+only has to stay under 1.5 s, and start-up under 1 s. GitHub's macOS runners are slower than
+a desk Mac (sleep-tabs: 1016 ms longest, 52 over 50 ms), and the budgets fit both. On 1 Nov 2026 every new tab blocked the main thread for
+about 100 ms, the first page shown for up to 330 ms, and turning developer mode on or off
+130–650 ms; `fifty-tabs` and `sleep-tabs` carry counts that allow the first. Lower the
+budgets as those get faster. Stalls right after a `snapshot` line are the snapshot being
+drawn and don't count.
+
+## Lint rules
+
+`scripts/lint.py` grandfathers existing code in `Tests/lint-baseline.txt`: a file that gains
+a finding fails, and when one loses a finding the baseline comes down
+(`scripts/lint.py --update-baseline`).
+
+- `layer-colour-outside-transaction`: a colour or opacity set on a `CALayer` Cra made itself,
+ outside a `CATransaction` with actions disabled, animates for 0.25 s.
+- `timer-outside-scheduler`: `Timer.scheduledTimer` in `App/`, `Services/` or `Model/`.
+- `wall-clock-in-decision`: `Date()` in the store, tab sleep or live folders.
+- `raw-observation-tracking`: `withObservationTracking` outside CraCore's
+ `observeChanges(of:apply:)`. A struct copied out before the closure is never tracked.
+- `importer-without-fixture`: an `…Importer` with no profile under `Tests/Fixtures`.
+
+## Faults
+
+`CraLog.fault("…")` is for a state the code assumes never happens: a file that can't be read
+or written, a sidebar whose links disagree. It writes a `fault:` line to `cra.log` instead of
+failing silently. Scenarios fail on any, and `CRA_FAULT_TRAP=1` makes a debug build stop at
+one. Every launch checks the sidebar and logs a fault for each broken link.
+
+## Scenarios
+
+ scripts/scenario.sh fifty-tabs # one
+ scripts/scenario.sh all # every one, about 6 minutes
+
+A scenario (`Tests/Scenarios/*.scenario`) is a list of `cra://` commands plus a few
+directives (`wait`, `repeat`, `budget`, `helpers`, `relaunch`, `expect-log`, `snapshot`;
+the header of `scripts/scenario.sh` lists them). It runs `build/Cra.app` on a throwaway data
+folder, behind your windows (`CRA_TEST_BACKGROUND`), with the fixture pages served from
+127.0.0.1. Logs, hitch log and snapshots land in `build/scenarios/<name>/`. Adding a journey
+is a text file; the invariants come for free.
+
+`fullscreen` takes over a Space and runs only with `CRA_SCENARIO_SCREEN=1` (CI does).
+`CRA_FLAGS=backdrop=material` runs any scenario on the sidebar's `NSVisualEffectView` path
+instead of the private `CABackdropLayer` one (`FeatureFlags`); nightly runs both, so a macOS
+that breaks the private path fails a run instead of shipping.
+
+## Component snapshots
+
+`component-snapshots` imports the made-up Arc profile, sizes the window and draws the space
+header, favorites, sidebar rows, dock, URL pill, the toolbar in its normal, developer and
+split-pane forms and the split row. A difference over 0.05 % of pixels fails, with a red diff
+image next to the new snapshot.
+
+A reference is Cra's own drawing, so it can only be as right as Cra was when it was recorded.
+Before recording one again (`CRA_SNAPSHOT_RECORD=1 scripts/scenario.sh component-snapshots`),
+compare that view with Arc 1:1 on screen, and put both in the PR.
+
+## Nightly
+
+`.github/workflows/nightly.yml`: every scenario on both backdrop paths, the harnesses under
+AddressSanitizer, ThreadSanitizer and UBSan (`CRA_TEST_SWIFTC_FLAGS`), 400 000 fuzzed inputs
+(`scripts/fuzz.sh`), and on Mondays mutation testing. Xcode's toolchain has no libFuzzer on
+macOS, so the fuzzer mutates the fixtures itself with a fixed seed; a crash leaves its input
+in `build/fuzz/crash-input`.
diff --git a/scripts/compare-png.swift b/scripts/compare-png.swift
new file mode 100644
index 0000000..ef0bb70
--- /dev/null
+++ b/scripts/compare-png.swift
@@ -0,0 +1,44 @@
+// Compares a component snapshot with its reference (scripts/scenario.sh `snapshot`):
+// xcrun swift scripts/compare-png.swift <reference.png> <new.png> [<diff.png>]
+// (scripts/scenario.sh compiles it once per run.)
+// Fails when the sizes differ, or when more than 0.05 % of pixels differ by more than 12/255 in
+// any channel (anti-aliasing moves a little between machines; geometry and colour do not).
+// The diff image shows changed pixels in red over a faded copy of the reference.
+import AppKit
+
+func pixels(_ path: String) -> (w: Int, h: Int, data: [UInt8])? {
+ guard let file = try? Data(contentsOf: URL(fileURLWithPath: path)), let cg = NSBitmapImageRep(data: file)?.cgImage else { return nil }
+ let w = cg.width, h = cg.height
+ var data = [UInt8](repeating: 0, count: w * h * 4)
+ guard let ctx = CGContext(data: &data, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4,
+ space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }
+ ctx.draw(cg, in: CGRect(x: 0, y: 0, width: w, height: h))
+ return (w, h, data)
+}
+
+let args = CommandLine.arguments
+guard args.count >= 3, let a = pixels(args[1]), let b = pixels(args[2]) else {
+ print("cannot read \(args.dropFirst().joined(separator: " "))"); exit(2)
+}
+guard a.w == b.w, a.h == b.h else { print("size \(b.w)x\(b.h), reference \(a.w)x\(a.h)"); exit(1) }
+var changed = 0
+var diff = [UInt8](repeating: 0, count: a.data.count)
+for i in stride(from: 0, to: a.data.count, by: 4) {
+ let d = (0..<4).map { abs(Int(a.data[i + $0]) - Int(b.data[i + $0])) }.max()!
+ if d > 12 {
+ changed += 1
+ diff[i] = 255; diff[i + 3] = 255
+ } else {
+ for k in 0..<3 { diff[i + k] = UInt8(min(255, Int(a.data[i + k]) / 4 + 191)) }
+ diff[i + 3] = 255
+ }
+}
+let share = Double(changed) / Double(a.w * a.h)
+if args.count > 3, changed > 0,
+ let ctx = CGContext(data: &diff, width: a.w, height: a.h, bitsPerComponent: 8, bytesPerRow: a.w * 4,
+ space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue),
+ let image = ctx.makeImage() {
+ try? NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: args[3]))
+}
+print(String(format: "%d pixels differ (%.3f %%)", changed, share * 100))
+exit(share > 0.0005 ? 1 : 0)
diff --git a/scripts/coverage.py b/scripts/coverage.py
new file mode 100755
index 0000000..4dc265a
--- /dev/null
+++ b/scripts/coverage.py
@@ -0,0 +1,174 @@
+#!/usr/bin/env python3 -I
+"""Line coverage of the test harnesses, and the gate that matters: changed lines.
+
+ scripts/coverage.py against origin/main
+ scripts/coverage.py --base <ref>
+
+Runs every harness (scripts/test-*.sh, Tests/test-*.sh) compiled with coverage, plus CraCore's
+`swift test --enable-code-coverage` when Packages/CraCore exists, and reports:
+
+ - each measured source file's line coverage;
+ - changed lines: of the lines this branch added or changed in files a harness compiles,
+ how many ran. Below 70 % fails: new code pays its own way, nothing old has to be backfilled;
+ - CraCore below 85 % fails (pure code, every line a decision);
+ - changed files no harness compiles (views, CEF glue) are listed, not counted: they are
+ covered by scenarios (scripts/scenario.sh), not by percentages.
+
+The summary goes to stdout and, in CI, to the job summary (GITHUB_STEP_SUMMARY).
+"""
+import glob
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+CHANGED_MIN = 70.0
+CORE_MIN = 85.0
+NOT_HARNESSES = {"scripts/test-update.sh", "scripts/test.sh"}
+
+
+def run(cmd, **kw):
+ return subprocess.run(cmd, cwd=ROOT, check=True, text=True, capture_output=True, **kw).stdout
+
+
+def harness_coverage(work):
+ """{file: {line: count}} over every harness binary."""
+ keep = os.path.join(work, "bin")
+ os.makedirs(keep)
+ env = dict(os.environ, CRA_TEST_SWIFTC_FLAGS="-profile-generate -profile-coverage-mapping",
+ CRA_TEST_KEEP=keep, LLVM_PROFILE_FILE=os.path.join(work, "%p-%m.profraw"))
+ scripts = sorted(glob.glob(os.path.join(ROOT, "scripts/test-*.sh")) + glob.glob(os.path.join(ROOT, "Tests/test-*.sh")))
+ for s in scripts:
+ rel = os.path.relpath(s, ROOT)
+ if rel in NOT_HARNESSES:
+ continue
+ r = subprocess.run(["bash", s], cwd=ROOT, env=env, text=True, capture_output=True)
+ if r.returncode != 0:
+ sys.exit(f"{rel} failed:\n{r.stdout[-2000:]}{r.stderr[-2000:]}")
+ raws = glob.glob(os.path.join(work, "*.profraw"))
+ binaries = sorted(glob.glob(os.path.join(keep, "*")))
+ if not raws or not binaries:
+ return {}
+ merged = os.path.join(work, "merged.profdata")
+ run(["xcrun", "llvm-profdata", "merge", "-sparse", "-o", merged] + raws)
+ objects = [binaries[0]] + [a for b in binaries[1:] for a in ("-object", b)]
+ return lcov_lines(run(["xcrun", "llvm-cov", "export", "-format=lcov", "-instr-profile", merged] + objects))
+
+
+def core_coverage():
+ pkg = os.path.join(ROOT, "Packages/CraCore")
+ if not os.path.isdir(pkg):
+ return {}
+ run(["swift", "test", "--package-path", pkg, "--enable-code-coverage"])
+ path = run(["swift", "test", "--package-path", pkg, "--show-codecov-path"]).strip()
+ data = json.load(open(path))
+ lines = {}
+ for f in data["data"][0]["files"]:
+ counts = lines.setdefault(f["filename"], {})
+ # Segments: [line, col, count, hasCount, isRegionEntry, (isGapRegion)]
+ for seg in f["segments"]:
+ if seg[3] and not (len(seg) > 5 and seg[5]):
+ counts[seg[0]] = max(counts.get(seg[0], 0), seg[2])
+ return lines
+
+
+def lcov_lines(text):
+ out, current = {}, None
+ for line in text.splitlines():
+ if line.startswith("SF:"):
+ current = out.setdefault(line[3:], {})
+ elif line.startswith("DA:") and current is not None:
+ n, count = line[3:].split(",")[:2]
+ current[int(n)] = max(current.get(int(n), 0), int(count))
+ return out
+
+
+def changed_lines(base):
+ merge_base = run(["git", "merge-base", base, "HEAD"]).strip()
+ diff = run(["git", "diff", "-U0", merge_base, "--", "Sources", "Packages"])
+ out, current = {}, None
+ for line in diff.splitlines():
+ if line.startswith("+++ "):
+ path = line[4:]
+ current = None if path == "/dev/null" else out.setdefault(os.path.join(ROOT, path[2:]), set())
+ elif line.startswith("@@") and current is not None:
+ m = re.match(r"@@ -\S+ \+(\d+)(?:,(\d+))? @@", line)
+ start, count = int(m.group(1)), int(m.group(2) or "1")
+ current.update(range(start, start + count))
+ # Uncommitted work counts too (a local run before committing).
+ for path in run(["git", "diff", "--name-only", "HEAD", "--", "Sources", "Packages"]).split():
+ out.setdefault(os.path.join(ROOT, path), set())
+ return out
+
+
+def pct(hit, total):
+ return 100.0 * hit / total if total else 100.0
+
+
+def main():
+ base = sys.argv[sys.argv.index("--base") + 1] if "--base" in sys.argv else "origin/main"
+ work = tempfile.mkdtemp(prefix="cra-coverage.")
+ try:
+ cov = harness_coverage(work)
+ core = core_coverage()
+ finally:
+ shutil.rmtree(work, ignore_errors=True)
+ for f, lines in core.items():
+ cov.setdefault(f, {}).update(lines)
+
+ table = ["| File | Lines | Covered |", "|---|---:|---:|"]
+ for f in sorted(cov):
+ if not f.startswith(ROOT) or "/Tests/" in f:
+ continue
+ lines = cov[f]
+ hit = sum(1 for c in lines.values() if c > 0)
+ table.append(f"| {os.path.relpath(f, ROOT)} | {len(lines)} | {pct(hit, len(lines)):.0f} % |")
+
+ report, failed = [], []
+ core_lines = [c for f, lines in core.items() if "/Sources/" in f for c in lines.values()]
+ if core_lines:
+ core_pct = pct(sum(1 for c in core_lines if c > 0), len(core_lines))
+ report.append(f"CraCore: {core_pct:.1f} % of {len(core_lines)} lines (minimum {CORE_MIN:.0f} %)")
+ if core_pct < CORE_MIN:
+ failed.append(f"CraCore coverage {core_pct:.1f} % < {CORE_MIN:.0f} %")
+
+ changed = changed_lines(base)
+ measured, hit, uncovered, unmeasured = 0, 0, [], []
+ for f, lines in sorted(changed.items()):
+ if f not in cov:
+ if f.endswith(".swift") and "/Tests/" not in f:
+ unmeasured.append(os.path.relpath(f, ROOT))
+ continue
+ executable = [n for n in lines if n in cov[f]]
+ measured += len(executable)
+ missed = sorted(n for n in executable if cov[f][n] == 0)
+ hit += len(executable) - len(missed)
+ if missed:
+ uncovered.append(f"{os.path.relpath(f, ROOT)}: {', '.join(map(str, missed[:30]))}{' …' if len(missed) > 30 else ''}")
+ changed_pct = pct(hit, measured)
+ report.insert(0, f"Changed lines under test: {hit} of {measured} ran ({changed_pct:.1f} %, minimum {CHANGED_MIN:.0f} %)\n")
+ if uncovered:
+ report.append("Changed lines no test ran:\n" + "\n".join(f"- {u}" for u in uncovered))
+ if unmeasured:
+ report.append("Changed files no harness compiles (scenarios cover these):\n" + "\n".join(f"- {u}" for u in unmeasured))
+ if measured and changed_pct < CHANGED_MIN:
+ failed.append(f"changed-lines coverage {changed_pct:.1f} % < {CHANGED_MIN:.0f} %")
+
+ report.append("\n<details><summary>Every measured file</summary>\n\n" + "\n".join(table) + "\n\n</details>")
+ text = "\n".join(report)
+ print(text)
+ if os.environ.get("GITHUB_STEP_SUMMARY"):
+ with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as f:
+ f.write("## Coverage\n\n" + text + "\n")
+ if failed:
+ print("coverage: " + "; ".join(failed))
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/fuzz.sh b/scripts/fuzz.sh
new file mode 100755
index 0000000..1cd615e
--- /dev/null
+++ b/scripts/fuzz.sh
@@ -0,0 +1,16 @@
+#!/bin/bash
+# Mutated copies of the importer fixtures through their parsers, under AddressSanitizer
+# (Tests/FuzzTests.swift). CRA_FUZZ_ITERATIONS (default 20000) and CRA_FUZZ_SEED; a crash
+# leaves its input in build/fuzz/crash-input.
+set -euo pipefail
+cd "$(dirname "$0")/.."
+TEST_DIR="$(mktemp -d /tmp/cra-fuzz.XXXXXX)"
+trap 'rm -rf "$TEST_DIR"' EXIT
+mkdir -p build/fuzz
+xcrun swiftc -swift-version 5 -parse-as-library -sanitize=address -g \
+ Packages/CraCore/Sources/CraCore/*.swift Sources/Cra/Model/*.swift Sources/Cra/Services/Import/*.swift \
+ Sources/Cra/Services/SidebarStore.swift Sources/Cra/Services/SidebarIntegrity.swift Sources/Cra/Services/Persistence.swift \
+ Sources/Cra/Services/ItemTable.swift Sources/Cra/Services/GitHubLiveClient.swift Sources/Cra/Services/FaviconCache.swift \
+ Sources/Cra/Services/SafeStorage.swift Sources/Cra/Services/CraLog.swift Sources/Cra/Services/Scheduler.swift \
+ Tests/FuzzTests.swift -o "$TEST_DIR/fuzz"
+CRA_FUZZ_OUT="$PWD/build/fuzz" "$TEST_DIR/fuzz"
diff --git a/scripts/lint.py b/scripts/lint.py
new file mode 100755
index 0000000..7221974
--- /dev/null
+++ b/scripts/lint.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python3 -I
+"""Cra's own lint: the bug classes that kept shipping, as rules over Sources/Cra.
+
+Existing code is grandfathered in Tests/lint-baseline.txt (rule, file, count); a file that
+gains a finding fails, one that loses one is reported so the baseline can come down
+(scripts/lint.py --update-baseline). Rules:
+
+ layer-colour-outside-transaction
+ A colour or opacity set on a CALayer Cra made itself (not a view's backing layer)
+ outside CATransaction.begin()/commit() with actions disabled animates for 0.25 s:
+ a flash on every theme or window-activation change. Inits are exempt (not on screen), and
+ so is a layer whose `actions` map the property to NSNull().
+ timer-outside-scheduler
+ Timer.scheduledTimer in App/, Services/ or Model/: decisions taken from time run on the
+ injectable clock (Scheduler), or no test can reach them. UI animation timers are exempt.
+ wall-clock-in-decision
+ Date() in a file whose decisions run on the clock (store, tab sleep, live folders).
+ raw-observation-tracking
+ withObservationTracking reached directly. The closure must read properties of an
+ @Observable class; a struct copied out before it (or a plain class) is never tracked and
+ the view silently stops updating. New sites go through CraCore's observeChanges(of:apply:),
+ where that is reviewed once.
+ importer-without-fixture
+ An importer (enum …Importer) without a checked-in profile under Tests/Fixtures/<Name>:
+ parsers are tested against files in the source browser's format, not dictionaries.
+"""
+import collections
+import os
+import re
+import sys
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+SOURCES = os.path.join(ROOT, "Sources", "Cra")
+BASELINE = os.path.join(ROOT, "Tests", "lint-baseline.txt")
+
+LAYER_SET = re.compile(r"\b(?!layer\b)(\w*[Ll]ayer)\.(backgroundColor|borderColor|colors|opacity|shadowColor|fillColor|strokeColor)\s*=")
+FUNC_START = re.compile(r"^\s*(?:@\w+\s+)*(?:(?:private|fileprivate|internal|public|override|static|final|class|nonisolated|convenience|required|@objc)\s+)*(func\s|init[(?!])")
+CLOCK_FILES = {"Services/SidebarStore.swift", "Services/BrowserManager.swift", "Services/LiveFolderManager.swift",
+ "Services/SidebarIntegrity.swift", "App/AppComposition.swift"}
+
+
+def swift_files():
+ for dirpath, _, names in os.walk(SOURCES):
+ for n in sorted(names):
+ if n.endswith(".swift"):
+ full = os.path.join(dirpath, n)
+ yield os.path.relpath(full, SOURCES), full
+
+
+def code(line):
+ """The line without a trailing // comment (good enough: no rule matches inside strings)."""
+ return line.split("//", 1)[0]
+
+
+def findings():
+ out = collections.Counter()
+ where = collections.defaultdict(list)
+
+ def hit(rule, rel, lineno):
+ out[(rule, rel)] += 1
+ where[(rule, rel)].append(lineno)
+
+ for rel, full in swift_files():
+ with open(full, encoding="utf-8") as f:
+ lines = f.readlines()
+ depth, in_init = 0, False
+ top = rel.split("/", 1)[0]
+ # Layers with the animation turned off for good: fillLayer.actions = ["backgroundColor": NSNull(), …]
+ quiet = {(name, prop) for name, body in re.findall(r"\b(\w+)\.actions\s*=\s*\[([^\]]*)\]", "".join(lines))
+ for prop in re.findall(r'"(\w+)"\s*:\s*NSNull\(\)', body)}
+ for i, raw in enumerate(lines, 1):
+ line = code(raw)
+ m = FUNC_START.match(line)
+ if m:
+ depth, in_init = 0, m.group(1).startswith("init")
+ depth += line.count("CATransaction.begin()") - line.count("CATransaction.commit()")
+ for m in LAYER_SET.finditer(line):
+ if depth <= 0 and not in_init and "setDisableActions" not in line and (m.group(1), m.group(2)) not in quiet:
+ hit("layer-colour-outside-transaction", rel, i)
+ if "Timer.scheduledTimer" in line and top in ("App", "Services", "Model") and rel != "Services/Scheduler.swift":
+ hit("timer-outside-scheduler", rel, i)
+ if rel in CLOCK_FILES and re.search(r"\bDate\(\)", line):
+ hit("wall-clock-in-decision", rel, i)
+ if "withObservationTracking" in line:
+ hit("raw-observation-tracking", rel, i)
+ for name in re.findall(r"\benum (\w+)Importer\b", line):
+ if not os.path.isdir(os.path.join(ROOT, "Tests", "Fixtures", name)):
+ hit("importer-without-fixture", f"{rel}:{name}", i)
+ return out, where
+
+
+def load_baseline():
+ base = collections.Counter()
+ if os.path.exists(BASELINE):
+ with open(BASELINE, encoding="utf-8") as f:
+ for line in f:
+ if line.strip() and not line.startswith("#"):
+ rule, rel, n = line.rstrip("\n").split("\t")
+ base[(rule, rel)] = int(n)
+ return base
+
+
+def main():
+ found, where = findings()
+ if "--update-baseline" in sys.argv:
+ with open(BASELINE, "w", encoding="utf-8") as f:
+ f.write("# scripts/lint.py findings in code older than the rule. Only ever lower these.\n")
+ for (rule, rel), n in sorted(found.items()):
+ f.write(f"{rule}\t{rel}\t{n}\n")
+ print(f"Baseline: {sum(found.values())} findings in {len(found)} files")
+ return 0
+ base = load_baseline()
+ failed = False
+ for key, n in sorted(found.items()):
+ if n > base.get(key, 0):
+ failed = True
+ rule, rel = key
+ lines = ", ".join(map(str, where[key]))
+ print(f"Sources/Cra/{rel.split(':')[0]}: {rule}: {n} (baseline {base.get(key, 0)}), lines {lines}")
+ lower = [(k, base[k], found.get(k, 0)) for k in sorted(base) if found.get(k, 0) < base[k]]
+ for (rule, rel), was, now in lower:
+ print(f"note: {rel}: {rule} down from {was} to {now}; run scripts/lint.py --update-baseline")
+ if failed:
+ print("lint: new findings (see the rule descriptions at the top of scripts/lint.py)")
+ return 1
+ print(f"lint: clean ({sum(found.values())} grandfathered findings)")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/mutate.py b/scripts/mutate.py
new file mode 100755
index 0000000..237f73d
--- /dev/null
+++ b/scripts/mutate.py
@@ -0,0 +1,103 @@
+#!/usr/bin/env python3 -I
+"""Mutation testing of the pure code: proof the tests assert something.
+
+Each mutant flips one operator (== to !=, < to >=, && to ||, true to false, + 1 to - 1,
+drops a !) in one of the files below and runs the tests that cover that file. A mutant the
+tests catch is killed; one they don't survives, and points at a decision nothing checks.
+Below 70 % killed fails. Weekly in CI (scripts take minutes: every mutant is a compile).
+
+ scripts/mutate.py every target
+ scripts/mutate.py DevToolsToggle targets whose path contains the word
+"""
+import glob
+import os
+import re
+import subprocess
+import sys
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+MIN_SCORE = 70.0
+
+# Pure decisions and the harness that checks them.
+TARGETS = [
+ ("Sources/Cra/Services/DevToolsToggle.swift", ["bash", "scripts/test-policies.sh"]),
+ ("Sources/Cra/UI/Windows/ExtensionLaunch.swift", ["bash", "scripts/test-policies.sh"]),
+ ("Sources/Cra/UI/ToolbarComposition.swift", ["bash", "scripts/test-policies.sh"]),
+ ("Sources/Cra/Services/SidebarIntegrity.swift", ["bash", "scripts/test-store.sh"]),
+ ("Sources/Cra/App/AppComposition.swift", ["bash", "scripts/test-store.sh"]),
+ ("Sources/Cra/App/FeatureFlags.swift", ["bash", "scripts/test-policies.sh"]),
+] + [(os.path.relpath(p, ROOT), ["swift", "test", "--package-path", "Packages/CraCore"])
+ for p in sorted(glob.glob(os.path.join(ROOT, "Packages/CraCore/Sources/CraCore/*.swift")))]
+
+OPERATORS = [
+ (r" == ", " != "), (r" != ", " == "), (r" < ", " >= "), (r" > ", " <= "), (r" <= ", " > "), (r" >= ", " < "),
+ (r" && ", " || "), (r" \|\| ", " && "), (r"\btrue\b", "false"), (r"\bfalse\b", "true"),
+ (r" \+ 1\b", " - 1"), (r" - 1\b", " + 1"), (r"(?<=[\s(,])!(?=[A-Za-z_(])", ""),
+]
+
+
+def mutants(text):
+ lines = text.split("\n")
+ for i, line in enumerate(lines):
+ stripped = line.strip()
+ if not stripped or stripped.startswith(("//", "///", "import ", "case ", "enum ", "struct ", "@")):
+ continue
+ code = line.split("//", 1)[0]
+ for pattern, repl in OPERATORS:
+ for m in re.finditer(pattern, code):
+ # Skip generics and string literals: crude, but a bad mutant only fails to compile.
+ if code.count('"', 0, m.start()) % 2:
+ continue
+ mutated = line[:m.start()] + repl + line[m.end():]
+ yield i + 1, f"{m.group(0).strip() or '!'} → {repl.strip() or '(nothing)'}", "\n".join(lines[:i] + [mutated] + lines[i + 1:])
+
+
+def main():
+ words = [a for a in sys.argv[1:] if not a.startswith("-")]
+ killed, survived, invalid = 0, [], 0
+ for rel, cmd in TARGETS:
+ if words and not any(w in rel for w in words):
+ continue
+ path = os.path.join(ROOT, rel)
+ if not os.path.exists(path):
+ continue
+ original = open(path, encoding="utf-8").read()
+ baseline = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True)
+ if baseline.returncode != 0:
+ sys.exit(f"{' '.join(cmd)} fails before any mutation:\n{baseline.stdout[-1500:]}{baseline.stderr[-1500:]}")
+ k = s = 0
+ try:
+ for line, what, text in mutants(original):
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(text)
+ try:
+ r = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, timeout=300)
+ out = r.stdout + r.stderr
+ except subprocess.TimeoutExpired:
+ k += 1 # a mutant that hangs the tests is caught
+ continue
+ if r.returncode == 0:
+ s += 1
+ survived.append(f"{rel}:{line}: {what}")
+ elif "error:" in out and "FAIL:" not in out and "failed" not in out.lower().split("error:")[0][-200:]:
+ invalid += 1 # did not compile: not a mutant
+ else:
+ k += 1
+ finally:
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(original)
+ killed += k
+ print(f"{rel}: {k} killed, {s} survived")
+ total = killed + len(survived)
+ score = 100.0 * killed / total if total else 100.0
+ print(f"\nMutation score: {score:.1f} % ({killed} of {total} killed, {invalid} did not compile)")
+ for s in survived:
+ print(f" survived {s}")
+ if os.environ.get("GITHUB_STEP_SUMMARY"):
+ with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as f:
+ f.write(f"## Mutation testing\n\n{score:.1f} % killed ({killed} of {total})\n\n" + "".join(f"- survived {s}\n" for s in survived))
+ return 0 if score >= MIN_SCORE else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/scenario.sh b/scripts/scenario.sh
new file mode 100755
index 0000000..e8a612b
--- /dev/null
+++ b/scripts/scenario.sh
@@ -0,0 +1,231 @@
+#!/bin/bash
+# Drives the real Cra.app through a user journey (Tests/Scenarios/<name>.scenario) on a
+# throwaway profile, behind your other windows, then checks the same invariants for every
+# scenario: still running, no new crash report, no fault in cra.log, the sidebar sound,
+# main-thread stalls and memory inside the scenario's budget, helper processes back to
+# baseline after tabs close, and a clean quit. Never asserts on pixels.
+#
+# scripts/scenario.sh fifty-tabs one scenario
+# scripts/scenario.sh all every scenario, one after another
+#
+# CRA_APP (default build/Cra.app) picks the build; CRA_FLAGS (FeatureFlags) is passed on, so
+# CRA_FLAGS=backdrop=material runs the NSVisualEffectView path. Scenarios marked
+# "requires screen" (they take over a Space) run only with CRA_SCENARIO_SCREEN=1, as in CI.
+# Logs land in build/scenarios/<name>/.
+#
+# Scenario lines: a cra:// command (sent through CRA_COMMAND_FILE, then `pace` seconds),
+# or one of
+# wait <s> let the app work
+# pace <s> pause after each command (default 0.2)
+# repeat <n> <cra://…${i}…> the command n times, ${i} = 1…n
+# budget rss=<MB> maxstall=<ms> stalls50=<n> launchstall=<ms>
+# (stalls count from the first command; start-up has its own launchstall budget)
+# helpers baseline | helpers settle [slack]
+# relaunch cra://debug?relaunch=1, then follow the new process
+# expect-log <regex> a line Cra logged (cra.log or stdout)
+# snapshot <View[,n]> <name> the nth visible view of that class drawn to PNG and compared with
+# Tests/Snapshots/<name>.png (CRA_SNAPSHOT_RECORD=1 records it)
+# fresh no seeded settings: onboarding shows, as on a new Mac
+# requires screen
+# port <n> serve ${PAGE} on a fixed port (snapshots show the address)
+# ${FIXTURES}, ${PAGE} (Tests/Fixtures/Pages/page.html from a local server, so it has a host
+# for developer mode and tab sleep) and ${EXTENSION_ID} (Tests/Fixtures/Extension) expand.
+set -uo pipefail
+cd "$(dirname "$0")/.."
+ROOT="$PWD"
+APP="${CRA_APP:-$ROOT/build/Cra.app}"
+FIXTURES="$ROOT/Tests/Fixtures"
+EXTENSION_ID="$(cat "$FIXTURES/Extension/ID")"
+
+if [ "${1:-}" = "all" ]; then
+ failed=()
+ for f in Tests/Scenarios/*.scenario; do
+ name="$(basename "$f" .scenario)"
+ "$0" "$name" || failed+=("$name")
+ done
+ [ ${#failed[@]} -eq 0 ] && { echo "All scenarios passed"; exit 0; }
+ echo "Failed: ${failed[*]}"; exit 1
+fi
+
+NAME="${1:?usage: scripts/scenario.sh <name>|all}"
+FILE="Tests/Scenarios/$NAME.scenario"
+[ -f "$FILE" ] || { echo "No scenario $FILE"; exit 2; }
+[ -x "$APP/Contents/MacOS/Cra" ] || { echo "No Cra at $APP (scripts/build.sh debug)"; exit 2; }
+if grep -q '^requires screen' "$FILE" && [ "${CRA_SCENARIO_SCREEN:-}" != "1" ]; then
+ echo "$NAME: skipped (takes over the screen; CRA_SCENARIO_SCREEN=1 runs it)"; exit 0
+fi
+
+OUT="$ROOT/build/scenarios/$NAME${CRA_FLAGS:+-${CRA_FLAGS//[^a-z]/}}"
+rm -rf "$OUT" && mkdir -p "$OUT"
+DATA="$(mktemp -d /tmp/cra-scenario.XXXXXX)"
+CMD="$OUT/commands"
+HITCH="$OUT/hitch.log"
+LOG="$DATA/cra.log"
+: > "$CMD"
+STARTED="$OUT/started"
+touch "$STARTED"
+# Past onboarding, and nothing taken from this Mac's Arc (its toolbar default) unless asked.
+grep -q '^fresh' "$FILE" || echo '{"hasSeenImportPrompt": true, "toolbarDefaultMigrated": true, "showToolbar": false}' > "$DATA/settings.json"
+
+PIDS=()
+PID=""
+FAULTS=0
+LOG_OFFSET=0
+PROBLEMS=()
+problem() { PROBLEMS+=("$1"); echo " ✗ $1"; }
+
+# The fixture pages over http on a free port: a real host, no network.
+FIXED_PORT=$(sed -n 's/^port \([0-9]*\).*/\1/p' "$FILE" | head -1)
+python3 -I -u -m http.server --bind 127.0.0.1 --directory "$FIXTURES/Pages" "${FIXED_PORT:-0}" >"$OUT/server.log" 2>&1 &
+SERVER=$!
+for _ in $(seq 1 50); do PORT=$(sed -n 's/.*port \([0-9]*\).*/\1/p' "$OUT/server.log" | head -1); [ -n "$PORT" ] && break; sleep 0.1; done
+PAGE="http://127.0.0.1:${PORT:?http server did not start}/page.html"
+
+CRA_DATA_DIR="$DATA" CRA_COMMAND_FILE="$CMD" CRA_HITCH_LOG="$HITCH" CRA_TEST_BACKGROUND=1 \
+ CRA_ARC_DIR="$FIXTURES/Arc" CRA_FLAGS="${CRA_FLAGS:-}" \
+ "$APP/Contents/MacOS/Cra" >"$OUT/stdout.log" 2>&1 &
+PID=$!
+PIDS+=("$PID")
+
+cleanup() {
+ for p in "${PIDS[@]}"; do kill -KILL "$p" 2>/dev/null; done
+ kill "$SERVER" 2>/dev/null
+ cp "$DATA"/cra*.log "$OUT/" 2>/dev/null
+ rm -rf "$DATA"
+}
+trap cleanup EXIT
+
+# Faults since the last count; a relaunch that rotated cra.log starts the count over.
+count_faults() {
+ [ -f "$LOG" ] || return
+ local lines; lines=$(wc -l < "$LOG" | tr -d ' ')
+ [ "$lines" -lt "$LOG_OFFSET" ] && LOG_OFFSET=0
+ FAULTS=$((FAULTS + $(tail -n +$((LOG_OFFSET + 1)) "$LOG" | grep -c ' fault: ')))
+ tail -n +$((LOG_OFFSET + 1)) "$LOG" | grep ' fault: ' >> "$OUT/faults.txt"
+ LOG_OFFSET=$lines
+}
+send() { printf '%s\n' "$1" >> "$CMD"; }
+helpers() { pgrep -P "$PID" 2>/dev/null | wc -l | tr -d ' '; }
+alive() { kill -0 "$PID" 2>/dev/null; }
+
+# Ready once Cra reads the command file (it empties the file when it starts reading).
+ready() {
+ for _ in $(seq 1 150); do grep -q "pid $1 reads commands" "$DATA"/cra*.log 2>/dev/null && return 0; sleep 0.2; done
+ return 1
+}
+ready "$PID" || problem "Cra did not start reading commands in 30 s"
+sleep 2
+
+PACE=0.2
+RSS_BUDGET=1500 MAXSTALL=1500 STALLS50=10 LAUNCHSTALL=1000
+BASELINE=""
+expand() { local s="$1"; s="${s//\$\{FIXTURES\}/$FIXTURES}"; s="${s//\$\{PAGE\}/$PAGE}"; s="${s//\$\{EXTENSION_ID\}/$EXTENSION_ID}"; printf '%s' "$s"; }
+
+echo "$NAME (pid $PID, logs in ${OUT#$ROOT/})"
+while IFS= read -r raw || [ -n "$raw" ]; do
+ line="$(expand "${raw%%#*}")"
+ line="${line%"${line##*[![:space:]]}"}"
+ [ -z "$line" ] && continue
+ alive || { problem "Cra exited during: $line"; break; }
+ set -f; set -- $line; set +f
+ case "$1" in
+ cra://*) send "$line"; sleep "$PACE" ;;
+ wait) sleep "$2" ;;
+ pace) PACE="$2" ;;
+ repeat)
+ n="$2"; shift 2; tmpl="$*"
+ for i in $(seq 1 "$n"); do send "${tmpl//\$\{i\}/$i}"; sleep "$PACE"; done ;;
+ budget)
+ shift
+ for kv in "$@"; do
+ case "$kv" in rss=*) RSS_BUDGET="${kv#*=}" ;; launchstall=*) LAUNCHSTALL="${kv#*=}" ;; maxstall=*) MAXSTALL="${kv#*=}" ;; stalls50=*) STALLS50="${kv#*=}" ;; esac
+ done ;;
+ helpers)
+ if [ "$2" = "baseline" ]; then BASELINE=$(helpers); echo " helpers: baseline $BASELINE"
+ else
+ slack="${3:-1}"; now=$(helpers)
+ for _ in $(seq 1 25); do now=$(helpers); [ "$now" -le $((BASELINE + slack)) ] && break; sleep 0.2; done
+ [ "$now" -le $((BASELINE + slack)) ] || problem "helper processes: $now, baseline $BASELINE (+$slack) after 5 s"
+ fi ;;
+ relaunch)
+ count_faults
+ # The next Cra starts its hitch log afresh: keep this one's.
+ { cat "$HITCH" 2>/dev/null; echo "0 relaunch"; } >> "$OUT/hitch.earlier"
+ old="$PID"; send "cra://debug?relaunch=1"
+ PID=""
+ for _ in $(seq 1 200); do
+ p=$(grep -ho 'starts, pid [0-9]*' "$DATA"/cra*.log 2>/dev/null | awk '{print $3}' | grep -vx "$old" | grep -vxF "$(printf '%s\n' "${PIDS[@]}")" | tail -1)
+ [ -n "$p" ] && kill -0 "$p" 2>/dev/null && { PID="$p"; break; }
+ sleep 0.2
+ done
+ [ -n "$PID" ] || { problem "no new Cra after relaunch"; PID="$old"; break; }
+ PIDS+=("$PID"); echo " relaunched: pid $PID"
+ ready "$PID" || problem "the relaunched Cra did not read commands in 30 s"
+ sleep 2 ;;
+ expect-log)
+ shift; re="$*"; found=""
+ for _ in $(seq 1 150); do grep -Eq "$re" "$DATA"/cra*.log "$OUT/stdout.log" 2>/dev/null && { found=1; break; }; sleep 0.2; done
+ [ -n "$found" ] || problem "no log line matching: $re" ;;
+ snapshot)
+ shot="$OUT/snapshots/$3.png"; ref="$ROOT/Tests/Snapshots/$3.png"
+ mkdir -p "$OUT/snapshots"; send "cra://debug?snapshot=$2&out=$shot"
+ for _ in $(seq 1 25); do [ -s "$shot" ] && break; sleep 0.2; done
+ if [ ! -s "$shot" ]; then problem "no snapshot of $2"
+ elif [ "${CRA_SNAPSHOT_RECORD:-}" = "1" ]; then mkdir -p "$ROOT/Tests/Snapshots"; cp "$shot" "$ref"; echo " recorded $3"
+ elif [ ! -f "$ref" ]; then problem "no reference Tests/Snapshots/$3.png (CRA_SNAPSHOT_RECORD=1 records one)"
+ else
+ [ -x "$OUT/compare-png" ] || xcrun swiftc -O "$ROOT/scripts/compare-png.swift" -o "$OUT/compare-png" 2>"$OUT/compare-png.log"
+ verdict=$("$OUT/compare-png" "$ref" "$shot" "$OUT/snapshots/$3.diff.png" 2>&1) || problem "snapshot $3: $verdict"
+ fi ;;
+ fresh|requires|port) ;;
+ *) problem "unknown scenario line: $line" ;;
+ esac
+done < "$FILE"
+
+# Invariants.
+if alive; then
+ send "cra://debug?checkStore=1"; sleep 1
+ rss=$(ps -o rss= -p "$PID" | tr -d ' ')
+ total=$(( rss + $(ps -o rss= -p "$(pgrep -P "$PID" | paste -sd, -)" 2>/dev/null | awk '{s+=$1} END {print s+0}') ))
+ echo " memory: Cra $((rss / 1024)) MB, with helpers $((total / 1024)) MB (budget $RSS_BUDGET MB for Cra)"
+ [ $((rss / 1024)) -le "$RSS_BUDGET" ] || problem "Cra uses $((rss / 1024)) MB, budget $RSS_BUDGET MB"
+else
+ problem "Cra is not running at the end"
+fi
+# Stalls after a snapshot command are the snapshot being drawn, not the app.
+read -r launch maxstall over50 < <(cat "$OUT/hitch.earlier" "$HITCH" 2>/dev/null | awk '$2 == "relaunch" { started = 0 }
+ $2 == "mark" { started = 1; shooting = ($3 ~ /snapshot=/) }
+ $2 == "stall" && shooting { next }
+ $2 == "stall" && !started { if ($3 > l) l = $3 }
+ $2 == "stall" && started { if ($3 > m) m = $3; if ($3 > 50) n++ }
+ END { printf "%d %d %d\n", l, m, n }' || echo "0 0 0")
+echo " stalls: start-up ${launch} ms (budget ${LAUNCHSTALL}); then longest ${maxstall} ms, ${over50} over 50 ms (budget ${MAXSTALL} ms, ${STALLS50})"
+[ "${launch:-0}" -le "$LAUNCHSTALL" ] || problem "a ${launch} ms main-thread stall at start-up, budget ${LAUNCHSTALL} ms"
+[ "${maxstall:-0}" -le "$MAXSTALL" ] || problem "a ${maxstall} ms main-thread stall, budget ${MAXSTALL} ms"
+[ "${over50:-0}" -le "$STALLS50" ] || problem "${over50} stalls over 50 ms, budget ${STALLS50}"
+
+# A clean quit, within the CefShutdown watchdog.
+if alive; then
+ send "cra://debug?quit=1"
+ for _ in $(seq 1 100); do alive || break; sleep 0.2; done
+ alive && problem "Cra did not quit within 20 s"
+fi
+count_faults
+[ "$FAULTS" -eq 0 ] || problem "$FAULTS fault line(s) in cra.log (faults.txt)"
+
+# Crash reports written for any of this run's processes (ReportCrash needs a moment).
+sleep 3
+for f in $(find "$HOME/Library/Logs/DiagnosticReports" -name '*.ips' -newer "$STARTED" 2>/dev/null); do
+ for p in "${PIDS[@]}"; do
+ if grep -Eq "\"(pid|parentPid)\" *: *$p[^0-9]" "$f"; then
+ problem "crash report $(basename "$f")"; cp "$f" "$OUT/"; break
+ fi
+ done
+done
+
+result="passed"; [ ${#PROBLEMS[@]} -eq 0 ] || result="FAILED"
+echo "$NAME: $result"
+if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then
+ echo "| $NAME${CRA_FLAGS:+ ($CRA_FLAGS)} | $result | ${maxstall:-?} ms / ${over50:-?} | ${rss:+$((rss / 1024)) MB} | ${PROBLEMS[*]:-} |" >> "$GITHUB_STEP_SUMMARY"
+fi
+[ ${#PROBLEMS[@]} -eq 0 ]
diff --git a/scripts/test-extension-popup-candidate.sh b/scripts/test-extension-popup-candidate.sh
index 5f1232d..9436cb9 100755
--- a/scripts/test-extension-popup-candidate.sh
+++ b/scripts/test-extension-popup-candidate.sh
@@ -3,6 +3,7 @@ set -euo pipefail
cd "$(dirname "$0")/.."
TEST_DIR="$(mktemp -d /tmp/cra-popup-candidate.XXXXXX)"
trap 'rm -rf "$TEST_DIR"' EXIT
-xcrun swiftc -parse-as-library Sources/Cra/UI/Windows/ExtensionPopupCandidate.swift \
+xcrun swiftc -parse-as-library ${CRA_TEST_SWIFTC_FLAGS:-} Sources/Cra/UI/Windows/ExtensionPopupCandidate.swift \
Tests/ExtensionPopupCandidateTests.swift -o "$TEST_DIR/candidate-tests"
"$TEST_DIR/candidate-tests"
+[ -z "${CRA_TEST_KEEP:-}" ] || cp "$TEST_DIR/candidate-tests" "$CRA_TEST_KEEP/"
diff --git a/scripts/test-extension-state.sh b/scripts/test-extension-state.sh
index aa2059f..4b1dbd9 100755
--- a/scripts/test-extension-state.sh
+++ b/scripts/test-extension-state.sh
@@ -3,6 +3,7 @@ set -euo pipefail
cd "$(dirname "$0")/.."
TEST_DIR="$(mktemp -d /tmp/cra-extension-state.XXXXXX)"
trap 'rm -rf "$TEST_DIR"' EXIT
-xcrun swiftc -parse-as-library Sources/Cra/Services/Import/ExtensionImporter.swift \
+xcrun swiftc -parse-as-library ${CRA_TEST_SWIFTC_FLAGS:-} Sources/Cra/Services/Import/ExtensionImporter.swift \
Tests/ExtensionStateTests.swift -o "$TEST_DIR/extension-state-tests"
"$TEST_DIR/extension-state-tests"
+[ -z "${CRA_TEST_KEEP:-}" ] || cp "$TEST_DIR/extension-state-tests" "$CRA_TEST_KEEP/"
diff --git a/scripts/test-floating-sidebar.sh b/scripts/test-floating-sidebar.sh
index aa67cf9..116e5e5 100755
--- a/scripts/test-floating-sidebar.sh
+++ b/scripts/test-floating-sidebar.sh
@@ -4,7 +4,8 @@ set -euo pipefail
cd "$(dirname "$0")/.."
TEST_DIR="$(mktemp -d /tmp/cra-sidebar-tests.XXXXXX)"
trap 'rm -rf "$TEST_DIR"' EXIT
-xcrun swiftc -parse-as-library Sources/Cra/UI/Windows/FloatingSidebarGeometry.swift \
+xcrun swiftc -parse-as-library ${CRA_TEST_SWIFTC_FLAGS:-} Sources/Cra/UI/Windows/FloatingSidebarGeometry.swift \
Sources/Cra/UI/Windows/FloatingSidebar.swift Tests/FloatingSidebarTests.swift \
-o "$TEST_DIR/sidebar-tests"
"$TEST_DIR/sidebar-tests"
+[ -z "${CRA_TEST_KEEP:-}" ] || cp "$TEST_DIR/sidebar-tests" "$CRA_TEST_KEEP/"
diff --git a/scripts/test-policies.sh b/scripts/test-policies.sh
new file mode 100755
index 0000000..5b7ff25
--- /dev/null
+++ b/scripts/test-policies.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+# Decisions pulled out of the window controllers (toolbar buttons, extension clicks, DevTools toggle).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+TEST_DIR="$(mktemp -d /tmp/cra-policy-tests.XXXXXX)"
+trap 'rm -rf "$TEST_DIR"' EXIT
+xcrun swiftc -swift-version 5 -parse-as-library ${CRA_TEST_SWIFTC_FLAGS:-} \
+ Sources/Cra/UI/ToolbarComposition.swift Sources/Cra/UI/Windows/ExtensionLaunch.swift Sources/Cra/Services/DevToolsToggle.swift Sources/Cra/App/FeatureFlags.swift \
+ Tests/PolicyTests.swift -o "$TEST_DIR/policy-tests"
+"$TEST_DIR/policy-tests"
+[ -z "${CRA_TEST_KEEP:-}" ] || cp "$TEST_DIR/policy-tests" "$CRA_TEST_KEEP/"
diff --git a/scripts/test-store.sh b/scripts/test-store.sh
new file mode 100755
index 0000000..05b2140
--- /dev/null
+++ b/scripts/test-store.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+# The production store, AppComposition and importers on a manual clock; no CEF or AppKit windows.
+set -euo pipefail
+cd "$(dirname "$0")/.."
+TEST_DIR="$(mktemp -d /tmp/cra-store-tests.XXXXXX)"
+trap 'rm -rf "$TEST_DIR"' EXIT
+xcrun swiftc -swift-version 5 -parse-as-library ${CRA_TEST_SWIFTC_FLAGS:-} \
+ Packages/CraCore/Sources/CraCore/*.swift Sources/Cra/Model/*.swift Sources/Cra/Services/Import/*.swift \
+ Sources/Cra/Services/SidebarStore.swift Sources/Cra/Services/SidebarIntegrity.swift Sources/Cra/Services/Persistence.swift Sources/Cra/Services/ItemTable.swift \
+ Sources/Cra/Services/GitHubLiveClient.swift Sources/Cra/Services/FaviconCache.swift Sources/Cra/Services/SafeStorage.swift \
+ Sources/Cra/Services/CraLog.swift Sources/Cra/Services/Scheduler.swift \
+ Sources/Cra/App/AppComposition.swift Sources/Cra/App/FeatureFlags.swift \
+ Tests/Support/ManualScheduler.swift Tests/StoreTests.swift -o "$TEST_DIR/store-tests"
+"$TEST_DIR/store-tests"
+[ -z "${CRA_TEST_KEEP:-}" ] || cp "$TEST_DIR/store-tests" "$CRA_TEST_KEEP/"
diff --git a/scripts/test.sh b/scripts/test.sh
index a90dac0..c6771fa 100755
--- a/scripts/test.sh
+++ b/scripts/test.sh
@@ -20,6 +20,9 @@ if [ "${1:-}" != core ]; then
suite "Floating sidebar" scripts/test-floating-sidebar.sh
suite "Extension popup candidate" scripts/test-extension-popup-candidate.sh
suite "Extension state" scripts/test-extension-state.sh
+ suite "Store and importers" scripts/test-store.sh
+ suite "Policies" scripts/test-policies.sh
+ suite "Lint" scripts/lint.py
fi
if [ ${#failed[@]} -gt 0 ]; then