Repository Public
1import WebKit2import XCTest3@testable import SPBrowser45/// AURA (3.0) in real windows and tabs: Flow recording, private isolation, Constellation, Canvas, Orbit, Portal and Peek state.6@MainActor7final class AuraAppTests: XCTestCase {8 private var root: URL!9 private var environment: AppEnvironment!10 private var state: BrowserWindowState!11 private var privateState: BrowserWindowState!1213 override func setUp() async throws {14 root = FileManager.default.temporaryDirectory.appendingPathComponent("spb-aura-tests-" + UUID().uuidString, isDirectory: true)15 environment = AppEnvironment(root: root, secrets: InMemorySecretStore(),16 backend: BackendConfiguration(baseURL: URL(string: "http://127.0.0.1:9")!, relyingParty: "browser.test"))17 state = BrowserWindowState(environment: environment, profile: environment.defaultContext)18 privateState = BrowserWindowState(environment: environment, profile: try ProfileContext(privateFrom: environment.defaultContext))19 }2021 override func tearDown() async throws {22 state.teardown(); privateState.teardown()23 state = nil; privateState = nil24 await environment.removeAllWebsiteDataStores()25 environment = nil26 try? FileManager.default.removeItem(at: root)27 }2829 private func waitUntil(_ timeout: TimeInterval = 15, _ condition: () -> Bool) async -> Bool {30 let deadline = Date().addingTimeInterval(timeout)31 while Date() < deadline {32 if condition() { return true }33 try? await Task.sleep(for: .milliseconds(40))34 }35 return condition()36 }3738 private func search(_ query: String, in tab: BrowserTab, of window: BrowserWindowState) async -> Bool {39 window.navigate(query, in: tab)40 let url = tab.url41 return await waitUntil { !tab.isLoading && tab.webView?.url == url && window.profile.flow.trail.nodes.contains { $0.url == url?.absoluteString } }42 }4344 func testFlowRecordsThePathAndBackThenForwardDoesNotDuplicateSteps() async {45 let tab = state.newTab()46 let first = await search("first journey step", in: tab, of: state)47 let second = await search("second journey step", in: tab, of: state)48 XCTAssertTrue(first && second)49 var trail = state.profile.flow.trail50 XCTAssertEqual(trail.nodes.count, 2)51 XCTAssertEqual(trail.nodes.map(\.kind), [.search, .search])52 XCTAssertEqual(trail.nodes.first?.displayTitle, "first journey step")53 XCTAssertEqual(trail.journeys.count, 2, "each typed query starts a journey")54 XCTAssertEqual(state.flowCursor, trail.nodes.last?.id)5556 tab.goBack()57 let back = await waitUntil { self.state.flowCursor == trail.nodes.first?.id }58 XCTAssertTrue(back, "going back moves the cursor to the existing step")59 trail = state.profile.flow.trail60 XCTAssertEqual(trail.nodes.count, 2)6162 // Returning to a step from the map moves the tab there without adding a node.63 state.flowOpen(trail.nodes[1], inNewTab: false)64 let returned = await waitUntil { self.state.flowCursor == trail.nodes[1].id && !tab.isLoading }65 XCTAssertTrue(returned)66 XCTAssertEqual(state.profile.flow.trail.nodes.count, 2)6768 // Opening a step in a new tab branches from that step: the new tab stands on it.69 state.flowOpen(trail.nodes[0], inNewTab: true)70 let branchTab = state.selectedTab!71 XCTAssertNotEqual(branchTab.id, tab.id)72 XCTAssertEqual(state.profile.flow.trail.cursor[branchTab.id], trail.nodes[0].id)7374 // The trail is on disk for the regular profile.75 let file = environment.profileStore.directory(for: state.profile.profile).appendingPathComponent("flow.json")76 XCTAssertTrue(FileManager.default.fileExists(atPath: file.path))77 }7879 func testPrivateWindowsKeepTheirPathInMemoryOnly() async {80 let regularFile = environment.profileStore.directory(for: state.profile.profile).appendingPathComponent("flow.json")81 let tab = privateState.newTab()82 let done = await search("something private", in: tab, of: privateState)83 XCTAssertTrue(done)84 XCTAssertEqual(privateState.profile.flow.trail.nodes.count, 1, "the private window can show its own path")85 XCTAssertTrue(state.profile.flow.trail.nodes.isEmpty, "nothing reaches the regular profile's trail")86 if let data = try? Data(contentsOf: regularFile) { XCTAssertFalse(String(decoding: data, as: UTF8.self).contains("private")) }87 let everything = (try? FileManager.default.subpathsOfDirectory(atPath: root.path)) ?? []88 for path in everything where path.hasSuffix(".json") {89 let text = (try? String(contentsOf: root.appendingPathComponent(path), encoding: .utf8)) ?? ""90 XCTAssertFalse(text.contains("something private"), "\(path) must not mention a private page")91 }92 XCTAssertFalse(privateState.isEnabled(.showPortal))93 XCTAssertNil(privateState.canvasHost.capture, "no page capture is offered in a private window")94 privateState.sendTabs(to: nil)95 XCTAssertTrue(environment.services.mirror.records(SyncCollection.handoff).isEmpty, "a private window never hands tabs off")96 }9798 func testTurningFlowOffStopsRecordingAndClearingHistoryClearsThePath() async {99 let tab = state.newTab()100 _ = await search("kept", in: tab, of: state)101 XCTAssertEqual(state.profile.flow.trail.nodes.count, 1)102 environment.settings.flowEnabled = false103 state.navigate("not recorded", in: tab)104 let url = tab.url105 _ = await waitUntil { !tab.isLoading && tab.webView?.url == url }106 XCTAssertEqual(state.profile.flow.trail.nodes.count, 1)107 environment.clearHistory(since: nil)108 XCTAssertTrue(state.profile.flow.trail.nodes.isEmpty)109 }110111 func testOpenerIsRememberedAndFeedsConstellation() {112 let parent = state.newTab(url: URL(string: "https://www.wikipedia.org/wiki/A"))113 let child = state.newTab(url: URL(string: "https://en.wikipedia.org/wiki/B"), select: false, after: parent)114 let other = state.newTab(url: URL(string: "https://example.com/"))115 XCTAssertEqual(child.openerID, parent.id)116 XCTAssertEqual(child.snapshot().openerID, parent.id)117 XCTAssertEqual(BrowserTab(snapshot: child.snapshot(), profile: state.profile, environment: environment).openerID, parent.id)118119 let items = state.constellationItems120 XCTAssertEqual(items.count, 3)121 let map = ConstellationMap(items: items)122 XCTAssertTrue(map.links.contains(ConstellationMap.Link(from: parent.id, to: child.id, kind: .parent)))123 XCTAssertEqual(map.clusters.first { $0.kind == .domain }?.label, "wikipedia.org")124125 // Selecting several tabs in the constellation makes one existing-style tab group.126 state.constellationGroup([parent.id, other.id])127 XCTAssertNotNil(parent.groupID)128 XCTAssertEqual(parent.groupID, other.groupID)129 XCTAssertEqual(state.groups.count, 1)130 // Dropping a tab on a group constellation joins it; dropping it on a site constellation leaves the group.131 let grouped = ConstellationMap(items: state.constellationItems)132 let groupCluster = grouped.clusters.first { $0.kind == .group }!133 state.constellationMove(child.id, to: groupCluster)134 XCTAssertEqual(child.groupID, parent.groupID)135 state.constellationMove(child.id, to: ConstellationMap.Cluster(id: "d:x", kind: .domain, label: "x", colorIndex: 0, center: .zero, radius: 10, members: []))136 XCTAssertNil(child.groupID)137 state.constellationClose([other.id])138 XCTAssertNil(state.tab(id: other.id))139 state.constellationOpen(child.id)140 XCTAssertEqual(state.selectedTabID, child.id)141 XCTAssertEqual(state.auraOverlay, .none)142 }143144 func testCommandsOpenAndCloseTheAuraSurfaces() {145 _ = state.newTab(url: URL(string: "https://example.com/"))146 for (command, overlay) in [(CommandID.showConstellation, AuraOverlay.constellation), (.showFlow, .flow), (.showCanvas, .canvas), (.showPortal, .portal)] {147 state.perform(command)148 XCTAssertEqual(state.auraOverlay, overlay)149 state.perform(command)150 XCTAssertEqual(state.auraOverlay, .none, "the same command closes the surface")151 }152 state.perform(.commandOrbit)153 XCTAssertTrue(state.orbitVisible)154 XCTAssertFalse(state.paletteVisible)155 // Typing in Orbit hands over to the one palette.156 state.orbitHandOver("can")157 XCTAssertFalse(state.orbitVisible)158 XCTAssertTrue(state.paletteVisible)159 XCTAssertEqual(state.palettePrefill, "can")160 state.paletteVisible = false161 state.perform(.commandOrbit)162 state.orbitRun(.toggleFocusMode)163 XCTAssertFalse(state.orbitVisible)164 XCTAssertTrue(state.focusMode, "Orbit runs commands through the same dispatcher")165 let ring = OrbitCatalog.ring(for: state.orbitContext)166 XCTAssertTrue(ring.contains(.addToCanvas))167 XCTAssertTrue(ring.allSatisfy { CommandID.allCases.contains($0) })168 XCTAssertFalse(state.isEnabled(.peekLink), "nothing is hovered")169 }170171 func testAddingThePageToTheCanvasPersistsACardAndNothingIsSyncedByDefault() {172 _ = state.newTab(url: URL(string: "https://example.com/article"))173 XCTAssertTrue(state.isEnabled(.addToCanvas))174 state.perform(.addToCanvas)175 let board = state.canvas.board176 XCTAssertEqual(board.cards.map(\.url), ["https://example.com/article"])177 XCTAssertEqual(board.cards.first?.kind, .tab)178 XCTAssertFalse(board.isSynced)179 XCTAssertNotNil(state.toast)180 // A second window of the same profile sees the same board from disk.181 XCTAssertEqual(CanvasStore(directory: environment.profileStore.directory(for: state.profile.profile).appendingPathComponent("Canvas")).board(board.id)?.cards.count, 1)182 environment.services.sync.requestSync(after: 0)183 XCTAssertTrue(environment.services.mirror.records(SyncCollection.canvas).isEmpty, "a board is only synchronized after the user opts in")184 // The private window shares the profile's boards (explicit additions, like bookmarks).185 XCTAssertEqual(privateState.canvas.board.id, board.id)186 let blank = BrowserWindowState(environment: environment, profile: environment.defaultContext)187 _ = blank.newTab()188 XCTAssertFalse(blank.isEnabled(.addToCanvas))189 blank.teardown()190 }191192 func testPeekStateFollowsTheHoveredLinkAndRefusesLocalTargets() async {193 let tab = state.newTab(url: URL(string: "https://example.com/"))194 tab.handleBridgeMessage(["t": "hover", "href": "https://example.org/next", "text": "Next", "x": 10, "y": 20, "w": 100, "h": 20, "vw": 1000, "vh": 800, "alt": true])195 XCTAssertEqual(tab.hovered?.url.absoluteString, "https://example.org/next")196 XCTAssertEqual(tab.hoveredLink, "https://example.org/next")197 XCTAssertTrue(state.isEnabled(.peekLink))198 state.perform(.peekLink)199 XCTAssertEqual(state.peek?.url.absoluteString, "https://example.org/next")200 XCTAssertTrue(state.peekActions.contains { $0.id == "later" })201 XCTAssertTrue(state.peekActions.contains { $0.id == "compare" })202 state.dismissPeek()203 XCTAssertNil(state.peek)204205 tab.handleBridgeMessage(["t": "hover", "href": "javascript:alert(1)"])206 XCTAssertNil(tab.hovered, "only http(s) links are ever reported")207208 // A public page pointing at the local network: the preview is refused, nothing is fetched.209 tab.handleBridgeMessage(["t": "hover", "href": "http://192.168.2.1/admin", "vw": 100, "vh": 100])210 state.perform(.peekLink)211 let refused = await waitUntil(5) { self.state.peek?.state == .refused }212 XCTAssertTrue(refused)213 state.dismissPeek()214215 tab.handleBridgeMessage(["t": "scroll", "p": 0.42, "tall": true])216 XCTAssertEqual(tab.readingProgress, 0.42, accuracy: 0.001)217 XCTAssertTrue(tab.isLongPage)218219 // In a private window the reading list is not offered from a preview.220 let privateTab = privateState.newTab(url: URL(string: "https://example.com/"))221 privateTab.handleBridgeMessage(["t": "hover", "href": "https://example.org/p", "vw": 100, "vh": 100])222 privateState.perform(.peekLink)223 XCTAssertFalse(privateState.peekActions.contains { $0.id == "later" })224 privateState.dismissPeek()225 }226227 func testThePageBridgeIsInstalledOnceAndReportsRealScrolling() async {228 let tab = state.newTab()229 let webView = tab.ensureWebView()230 XCTAssertEqual(webView.configuration.userContentController.userScripts.filter { $0.source == ReadingScripts.bridge }.count, 1)231 let paragraphs = (0..<400).map { "<p>Paragraph \($0) of a long page used to measure reading progress.</p>" }.joined()232 webView.loadHTMLString("<!doctype html><html><head><title>Long</title></head><body>\(paragraphs)<a id='l' href='https://example.org/target'>target</a></body></html>", baseURL: URL(string: "https://long.test/"))233 let loaded = await waitUntil { tab.title == "Long" && !tab.isLoading }234 XCTAssertTrue(loaded)235 _ = try? await webView.evaluateJavaScript("window.scrollTo(0, document.documentElement.scrollHeight)")236 let scrolled = await waitUntil(8) { tab.readingProgress > 0.9 }237 XCTAssertTrue(scrolled, "the bridge reports the scroll position from the isolated world (progress \(tab.readingProgress))")238 XCTAssertTrue(tab.isLongPage)239 // Reinstalling user scripts (settings change) keeps exactly one bridge.240 UserScriptInjector.install([], enabled: false, into: webView.configuration.userContentController)241 XCTAssertEqual(webView.configuration.userContentController.userScripts.filter { $0.source == ReadingScripts.bridge }.count, 1)242 }243244 func testHandoffIsSentFromRegularWindowsOnlyWhenSignedIn() {245 _ = state.newTab(url: URL(string: "https://example.com/"))246 state.sendTabs(to: nil)247 XCTAssertTrue(environment.services.mirror.records(SyncCollection.handoff).isEmpty, "signed out: nothing is queued")248 XCTAssertFalse(state.portalHost.canSend)249 XCTAssertFalse(state.portalHost.isSignedIn)250 XCTAssertTrue(environment.services.pendingHandoffs.isEmpty)251 }252253 func testSettingsSchemaAndAmbientThemeSurviveARelaunch() {254 environment.settings.startPage.ambient = .cosmos255 environment.settings.peekOnHover = true256 let again = AppEnvironment(root: root, secrets: InMemorySecretStore(), backend: BackendConfiguration(baseURL: URL(string: "http://127.0.0.1:9")!, relyingParty: "browser.test"))257 XCTAssertEqual(again.settings.startPage.ambient, .cosmos)258 XCTAssertTrue(again.settings.peekOnHover)259 XCTAssertEqual(again.settings.schemaVersion, 4)260 }261}262