Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
public import Foundation

/// Browser automation state that belongs to each surface's current top-level document.
///
/// `browser frame select` stores a CSS selector for the frame later commands
/// run in, and the element refs handed out by `browser snapshot` and the
/// `find` commands (`@e1`, `@e2`, ...) each stand for a CSS selector. A
/// selector only means something in the document it was resolved in, so the
/// owner reports every main-frame commit through
/// ``mainFrameDidCommit(surfaceID:)`` and that surface starts over: commands
/// run in the main frame and its old refs no longer resolve, rather than
/// being replayed against the next page.
///
/// The type is a value: the app's browser controller owns one instance and
/// serializes access to it.
///
/// ```swift
/// var state = BrowserAutomationDocumentState()
/// let document = state.documentGeneration(surfaceID: surfaceID)
/// state.selectFrame("#checkout", surfaceID: surfaceID, checkedInDocument: document)
/// let ref = state.allocateElementRef(selector: "#pay", surfaceID: surfaceID)
/// state.selector(forElementRef: ref, surfaceID: surfaceID) // "#pay"
/// ```
public struct BrowserAutomationDocumentState: Sendable {
private struct ElementRef: Sendable {
let surfaceID: UUID
let selector: String
}

private var nextElementOrdinal = 1
private var elementRefs: [String: ElementRef] = [:]
private var frameSelectors: [UUID: String] = [:]
private var commitCounts: [UUID: Int] = [:]

/// Creates a state with no selected frames and no element refs.
public init() {}

/// Returns the selector of the frame selected on a surface, or `nil` for the main frame.
/// - Parameter surfaceID: The browser surface to look up.
/// - Returns: The selector stored by ``selectFrame(_:surfaceID:)``, if any.
public func frameSelector(surfaceID: UUID) -> String? {
frameSelectors[surfaceID]
}

/// Identifies a surface's current top-level document among the ones it has committed.
///
/// Read it before checking a selector against the page, then pass it to
/// ``selectFrame(_:surfaceID:checkedInDocument:)``.
/// - Parameter surfaceID: The browser surface to look up.
/// - Returns: A value that changes with every ``mainFrameDidCommit(surfaceID:)``.
public func documentGeneration(surfaceID: UUID) -> Int {
commitCounts[surfaceID, default: 0]
}

/// Makes later commands on a surface run in the frame matching `selector`.
///
/// Checking the selector against the page takes a round trip to the web
/// process, and the page can commit a redirect meanwhile. The selection is
/// refused then, because the selector was checked in a document that is gone.
/// - Parameters:
/// - selector: CSS selector of a same-origin frame in the current document.
/// - surfaceID: The browser surface the selection applies to.
/// - generation: The ``documentGeneration(surfaceID:)`` read before the check.
/// - Returns: `false` when the surface committed a new document since `generation`.
@discardableResult
public mutating func selectFrame(
_ selector: String,
surfaceID: UUID,
checkedInDocument generation: Int
) -> Bool {
guard generation == documentGeneration(surfaceID: surfaceID) else { return false }
frameSelectors[surfaceID] = selector
return true
}

/// Makes later commands on a surface run in the main frame again.
/// - Parameter surfaceID: The browser surface to reset.
public mutating func selectMainFrame(surfaceID: UUID) {
frameSelectors.removeValue(forKey: surfaceID)
}

/// Hands out a new element ref for a selector on a surface.
///
/// Ordinals count up across all surfaces and are never reused, so a ref
/// that was dropped cannot later resolve to a different element.
/// - Parameters:
/// - selector: CSS selector the ref stands for.
/// - surfaceID: The browser surface the element was found on.
/// - Returns: The ref, in the form `@e<ordinal>`.
public mutating func allocateElementRef(selector: String, surfaceID: UUID) -> String {
let ref = "@e\(nextElementOrdinal)"
nextElementOrdinal += 1
elementRefs[ref] = ElementRef(surfaceID: surfaceID, selector: selector)
return ref
}

/// Returns the selector an element ref stands for on a surface.
/// - Parameters:
/// - ref: A ref returned by ``allocateElementRef(selector:surfaceID:)``.
/// - surfaceID: The browser surface the command targets.
/// - Returns: The selector, or `nil` when the ref is unknown or belongs to another surface.
public func selector(forElementRef ref: String, surfaceID: UUID) -> String? {
guard let entry = elementRefs[ref], entry.surfaceID == surfaceID else { return nil }
return entry.selector
}

/// Drops a surface's selected frame and element refs because its main frame committed a new document.
///
/// Reload, back, forward, a followed link and a script-driven navigation
/// all commit, so each returns the surface to the main frame and makes its
/// outstanding refs unresolvable. A same-document change (a fragment or
/// `history.pushState`) does not commit and keeps both.
/// - Parameter surfaceID: The browser surface whose top-level document was replaced.
public mutating func mainFrameDidCommit(surfaceID: UUID) {
frameSelectors.removeValue(forKey: surfaceID)
elementRefs = elementRefs.filter { $0.value.surfaceID != surfaceID }
commitCounts[surfaceID, default: 0] += 1
}

/// Forgets the selected frame and every element ref of a closed surface.
/// - Parameter surfaceID: The browser surface that went away.
public mutating func removeSurface(_ surfaceID: UUID) {
frameSelectors.removeValue(forKey: surfaceID)
elementRefs = elementRefs.filter { $0.value.surfaceID != surfaceID }
commitCounts.removeValue(forKey: surfaceID)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@ public enum BrowserStateLoadTransactionResult: Equatable {

/// Keeps browser state restoration ordered around the asynchronous WebKit load.
/// Cookies must be present before the request starts, and page storage belongs
/// to the document that actually committed the requested URL.
/// to the document that actually committed the requested URL. The saved frame
/// selection names a frame of that document, so it comes last and only when
/// everything before it succeeded.
public struct BrowserStateLoadTransaction: Sendable {
public init() {}

/// Restores cookies before navigation and page storage after its commit.
/// Restores cookies before navigation, then page storage and frame selection after its commit.
public func run(
hasNavigation: Bool,
restoreFrameSelection: () -> Void,
installCookies: () -> Bool,
navigateAndWait: () -> BrowserAutomationNavigationOutcome?,
applyStorage: () -> Bool
Expand All @@ -33,6 +36,7 @@ public struct BrowserStateLoadTransaction: Sendable {
}

guard applyStorage() else { return .storageWriteFailed }
restoreFrameSelection()
return .loaded
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import Foundation
import Testing

@testable import CmuxBrowser

@Suite("Browser automation document state")
struct BrowserAutomationDocumentStateTests {
private let checkout = UUID()
private let docs = UUID()

@Test("a selected frame applies to its own surface until the main frame is selected")
func frameSelectionIsPerSurface() {
var state = BrowserAutomationDocumentState()
#expect(state.frameSelector(surfaceID: checkout) == nil)

state.selectFrame("#checkout", surfaceID: checkout, checkedInDocument: state.documentGeneration(surfaceID: checkout))
#expect(state.frameSelector(surfaceID: checkout) == "#checkout")
#expect(state.frameSelector(surfaceID: docs) == nil)

state.selectMainFrame(surfaceID: checkout)
#expect(state.frameSelector(surfaceID: checkout) == nil)
}

@Test("element refs resolve only on the surface they were found on")
func elementRefsAreScopedToTheirSurface() {
var state = BrowserAutomationDocumentState()
let pay = state.allocateElementRef(selector: "#pay", surfaceID: checkout)
let search = state.allocateElementRef(selector: "#search", surfaceID: docs)

#expect(pay == "@e1")
#expect(search == "@e2")
#expect(state.selector(forElementRef: pay, surfaceID: checkout) == "#pay")
#expect(state.selector(forElementRef: pay, surfaceID: docs) == nil)
#expect(state.selector(forElementRef: "@e9", surfaceID: checkout) == nil)
}

@Test("closing a surface drops its frame and refs and leaves other surfaces alone")
func removingASurfaceDropsOnlyItsState() {
var state = BrowserAutomationDocumentState()
state.selectFrame("#checkout", surfaceID: checkout, checkedInDocument: state.documentGeneration(surfaceID: checkout))
state.selectFrame("#sidebar", surfaceID: docs, checkedInDocument: state.documentGeneration(surfaceID: docs))
let pay = state.allocateElementRef(selector: "#pay", surfaceID: checkout)
let search = state.allocateElementRef(selector: "#search", surfaceID: docs)

state.removeSurface(checkout)

#expect(state.frameSelector(surfaceID: checkout) == nil)
#expect(state.selector(forElementRef: pay, surfaceID: checkout) == nil)
#expect(state.frameSelector(surfaceID: docs) == "#sidebar")
#expect(state.selector(forElementRef: search, surfaceID: docs) == "#search")
}

/// The selected frame is a selector in the old page. Kept across a
/// navigation it either matches nothing, and commands silently run in the
/// new top document, or it matches an unrelated frame.
@Test("a main-frame commit returns the surface to the main frame")
func mainFrameCommitDropsTheSelectedFrame() {
var state = BrowserAutomationDocumentState()
state.selectFrame("#checkout", surfaceID: checkout, checkedInDocument: state.documentGeneration(surfaceID: checkout))
state.selectFrame("#sidebar", surfaceID: docs, checkedInDocument: state.documentGeneration(surfaceID: docs))

state.mainFrameDidCommit(surfaceID: checkout)

#expect(state.frameSelector(surfaceID: checkout) == nil)
#expect(state.frameSelector(surfaceID: docs) == "#sidebar")
}

@Test("a main-frame commit invalidates the surface's element refs for good")
func mainFrameCommitDropsElementRefs() {
var state = BrowserAutomationDocumentState()
let pay = state.allocateElementRef(selector: "#pay", surfaceID: checkout)
let search = state.allocateElementRef(selector: "#search", surfaceID: docs)

state.mainFrameDidCommit(surfaceID: checkout)

#expect(state.selector(forElementRef: pay, surfaceID: checkout) == nil)
#expect(state.selector(forElementRef: search, surfaceID: docs) == "#search")

// A ref from the old page must not come back to life for an element of the new one.
let next = state.allocateElementRef(selector: "#cancel", surfaceID: checkout)
#expect(next != pay)
#expect(state.selector(forElementRef: pay, surfaceID: checkout) == nil)
#expect(state.selector(forElementRef: next, surfaceID: checkout) == "#cancel")
}

/// `frame select` checks its selector in the page before storing it. A
/// redirect that commits during that check must not leave the selector
/// stored for the page it was never checked in.
@Test("a frame checked in a document that has since been replaced is not selected")
func frameCheckedInAReplacedDocumentIsRefused() {
var state = BrowserAutomationDocumentState()
let checkedIn = state.documentGeneration(surfaceID: checkout)

state.mainFrameDidCommit(surfaceID: checkout)

let selectedStale = state.selectFrame("#checkout", surfaceID: checkout, checkedInDocument: checkedIn)
#expect(!selectedStale)
#expect(state.frameSelector(surfaceID: checkout) == nil)

let current = state.documentGeneration(surfaceID: checkout)
let selectedCurrent = state.selectFrame("#checkout", surfaceID: checkout, checkedInDocument: current)
#expect(selectedCurrent)
#expect(state.frameSelector(surfaceID: checkout) == "#checkout")
#expect(state.documentGeneration(surfaceID: docs) == checkedIn)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ struct BrowserStateLoadTransactionTests {

let result = BrowserStateLoadTransaction().run(
hasNavigation: true,
restoreFrameSelection: {},
installCookies: {
events.append("cookies")
return true
Expand All @@ -37,6 +38,7 @@ struct BrowserStateLoadTransactionTests {

let result = BrowserStateLoadTransaction().run(
hasNavigation: true,
restoreFrameSelection: {},
installCookies: { true },
navigateAndWait: { .failed("offline") },
applyStorage: {
Expand All @@ -48,4 +50,71 @@ struct BrowserStateLoadTransactionTests {
#expect(result == .navigationFailed(.failed("offline")))
#expect(!storageApplied)
}

/// A saved frame selector names a frame of the page the state file loads,
/// so it can only be checked and applied once that page is there.
@Test("frame selection is restored after the loaded page has its storage")
func frameSelectionWaitsForTheLoadedDocument() {
var events: [String] = []

let result = BrowserStateLoadTransaction().run(
hasNavigation: true,
restoreFrameSelection: { events.append("frame") },
installCookies: {
events.append("cookies")
return true
},
navigateAndWait: {
events.append("navigate")
return .committed
},
applyStorage: {
events.append("storage")
return true
}
)

#expect(result == .loaded)
#expect(events == ["cookies", "navigate", "storage", "frame"])
}

@Test("a state file without a URL restores frame selection against the current page")
func frameSelectionIsRestoredWithoutNavigation() {
var events: [String] = []

let result = BrowserStateLoadTransaction().run(
hasNavigation: false,
restoreFrameSelection: { events.append("frame") },
installCookies: { true },
navigateAndWait: {
events.append("navigate")
return .committed
},
applyStorage: {
events.append("storage")
return true
}
)

#expect(result == .loaded)
#expect(events == ["storage", "frame"])
}

@Test("a failed load does not restore the saved frame selection", arguments: [
"cookies", "navigation", "storage",
])
func failedLoadLeavesFrameSelectionAlone(failingStep: String) {
var frameSelectionRestored = false

let result = BrowserStateLoadTransaction().run(
hasNavigation: true,
restoreFrameSelection: { frameSelectionRestored = true },
installCookies: { failingStep != "cookies" },
navigateAndWait: { failingStep == "navigation" ? .failed("offline") : .committed },
applyStorage: { failingStep != "storage" }
)

#expect(result != .loaded)
#expect(!frameSelectionRestored)
}
}
5 changes: 5 additions & 0 deletions Sources/Panels/BrowserPanel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3342,6 +3342,11 @@ final class BrowserPanel: Panel, ObservableObject {
WindowBrowserSlotView.hosting(webView)?.clearLinkHoverURLs()
self.isMainFrameProvisionalNavigationActive = false
self.automationDocumentReadiness.didCommit(instanceID: boundWebViewInstanceID)
NotificationCenter.default.post(
name: .browserMainFrameDidCommit,
object: self,
userInfo: ["surfaceId": self.id]
)
self.automationNavigationCoordinator.didCommit(
instanceID: boundWebViewInstanceID,
navigationID: navigation.map { ObjectIdentifier($0) }
Expand Down
Loading