An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(mac): the app approves browsers in ask mode: a sheet with the browser, its store, its version and a name field, a notification with Allow and Deny that counts only with its request's nonce, a dot and a menu item in the menu bar and a Dock bounce; Settings choose automatic, ask or code; the Browsers tab says how each paired, renames it, and lists the ones kept out with Reconnect; a browser that paired by itself is announced once
Shahriarbdbeaf27b7f4
diff --git a/docs/internals/mac-app.md b/docs/internals/mac-app.mdindex 1a605da..49b4547 100644--- a/docs/internals/mac-app.md+++ b/docs/internals/mac-app.md@@ -17,7 +17,7 @@ open socket rather than a `node` process every two seconds.| Path | Used for | Where || --- | --- | --- |-| **The control socket**: `ws://127.0.0.1:<port>/control`, bearer token from `daemon.json` | `status`, `sessions`, `pair`, `revoke`, `agent` set and grant, `preferences` and `setPreference` | [ControlClient.swift](../../src/mac/Sources/Browsentic/Core/ControlClient.swift), the same frames as [remote-bridge.ts](../../src/daemon/remote-bridge.ts) |+| **The control socket**: `ws://127.0.0.1:<port>/control`, bearer token from `daemon.json` | `status`, `sessions`, `pair`, `revoke`, `agent` set and grant, `preferences` and `setPreference`, and for pairing `pairRequests` (watched, as the approver), `decide`, `pairing`, `blocked` and `label` | [ControlClient.swift](../../src/mac/Sources/Browsentic/Core/ControlClient.swift), the same frames as [remote-bridge.ts](../../src/daemon/remote-bridge.ts) || **The installed command**: `node ~/.browsentic/cli/dist/cli.js …` | `start`, `stop`, `restart`, `setup`, `uninstall`, and the `--json` listings for `agent`, `skills`, `approvals`, `downloads` | [CLI.swift](../../src/mac/Sources/Browsentic/Core/CLI.swift) |Anything that reads or writes disk goes through the command, so config overrides (`downloadDir`,@@ -27,6 +27,18 @@ what keeps the daemon from idling out while the app is up.A `ControlRequest` change in [control.ts](../../src/daemon/control.ts) needs the matching change in`ControlClient.swift` and `Models.swift`; nothing checks that for you.+## Approving a browser++The app watches `pairRequests` on every socket, so it is the approver the Bridge names while it runs.+A browser that asks to pair in ask mode shows as a sheet in the main window (oldest first, with a+name field), a notification with Allow and Deny (`PairingAlerts.swift`; the delegate is set in+`applicationWillFinishLaunching` so a click that launches the app is not lost), a dot on the menu+bar icon with a menu item, and one Dock bounce. A notification's answer counts only while its+request still waits with the nonce the Bridge gave it. An ad-hoc signed build may never be granted+notifications; the sheet, the dot and the bounce carry the flow without them. When no app is+watching, the Bridge starts it with `open -g … --args --pairing`, which never takes focus. In auto+mode a browser that paired by itself gets one notice and one notification, with Unpair.+## The payload[build-app.sh](../../src/mac/Scripts/build-app.sh) stages `Contents/Resources/payload/` in the npmdiff --git a/src/mac/Sources/Browsentic/App/AppModel.swift b/src/mac/Sources/Browsentic/App/AppModel.swiftindex 8261b00..6446d50 100644--- a/src/mac/Sources/Browsentic/App/AppModel.swift+++ b/src/mac/Sources/Browsentic/App/AppModel.swift@@ -57,6 +57,8 @@ struct Notice: Identifiable, Equatable {@MainActorfinal class AppModel: ObservableObject {+ static let shared = AppModel()+@Published var phase: Phase = .preflight@Published var tab: Tab = .overview@Published var settingsSection: SettingsSection = .general@@ -90,6 +92,12 @@ final class AppModel: ObservableObject {@Published var lastUpdateCheck: Date?@Published var busy: Set<String> = []@Published var notice: Notice?+ /// Browsers waiting to be let in, oldest first; the approval sheet shows the first.+ @Published var pendingRequests: [PairRequest] = []+ @Published var pairingMode: PairingMode?+ @Published var blocked: [BlockedBrowser] = []+ /// Set by a view that can open the main window; the app delegate and the notifications cannot.+ var openMainWindow: (() -> Void)?private(set) var node: NodeInstall?private let control = ControlClient()@@ -97,6 +105,8 @@ final class AppModel: ObservableObject {private var eventWatcher: Task<Void, Never>?private var updateWatcher: Task<Void, Never>?private var watchingAndroid = false+ private var announcedRequests: Set<String> = []+ private var seenPairings: Set<String>?var cli: CLI? { node.map(CLI.init) }var appVersion: String { Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? Payload.bundledVersion ?? "dev" }@@ -106,6 +116,11 @@ final class AppModel: ObservableObject {return sessions.contains { $0.connected && $0.source == "unpacked" && $0.extensionVersion != stamp.version }}+ /// False for a Bridge from before automatic pairing, which never answers its ops.+ var bridgePairs: Bool { status?.pairing != nil }+ var mainWindow: NSWindow? { NSApp.windows.first(where: \.canBecomeMain) }+ var mainWindowVisible: Bool { NSApp.isActive && mainWindow?.isVisible == true }+/// The browsers worth a row: found on this Mac or already paired, else the usual few to try.var offeredBrowsers: [BrowserRow] {let found = browserRows.filter { $0.installed || !$0.sessions.isEmpty }@@ -242,22 +257,26 @@ final class AppModel: ObservableObject {// MARK: Daemon+ /// Runs once however often it is called: cancelling the task that reads the event stream would end the stream for good.func startPolling() {- eventWatcher?.cancel()- eventWatcher = Task { [weak self, control] in- for await event in control.events {- switch event {- case "settings-changed":- await self?.loadPreferences()- await self?.loadAgents()- case "android-changed":- await self?.loadAndroid()- default:- break+ if eventWatcher == nil {+ eventWatcher = Task { [weak self, control] in+ for await event in control.events {+ switch event {+ case "settings-changed":+ await self?.loadPreferences()+ await self?.loadAgents()+ case "android-changed":+ await self?.loadAndroid()+ case "pair-requests-changed":+ await self?.loadPairRequests()+ default:+ break+ }}}}- poller?.cancel()+ guard poller == nil else { return }poller = Task { [weak self] inwhile !Task.isCancelled {await self?.refresh()@@ -279,11 +298,14 @@ final class AppModel: ObservableObject {self.lock = lockself.status = statusself.sessions = sessions+ pairingMode = status.pairing?.kind+ noticePairedByThemselves(sessions)if daemon != .stopping { daemon = .on }if pairing != nil, !status.pairingPending || (pairing?.expiry ?? .distantPast) < Date() { pairing = nil }if agents == nil { await loadAgents() }stamp = ExtensionFiles.stamp()if changed { Task { await loadBrowsers() } }+ if status.pairing != nil { await loadPairRequests() }} catch {await control.close()markOff()@@ -298,6 +320,11 @@ final class AppModel: ObservableObject {sessions = []pairing = nilpreferences = nil+ pairingMode = nil+ blocked = []+ seenPairings = nil+ PairingAlerts.shared.withdraw(Set(pendingRequests.map(\.id)))+ pendingRequests = []}private static func readLock() -> Lockfile? {@@ -337,13 +364,109 @@ final class AppModel: ObservableObject {}func revoke(_ session: BrowserSession?) async {- await perform("revoke") { _, control in+ await onBridge("revoke") { control inlet count = try await control.revoke(session)self.say(count == 0 ? "Nothing to unpair." : "Unpaired \(count) browser\(count == 1 ? "" : "s").")}await refresh()}+ // MARK: Pairing++ func loadPairRequests() async {+ guard let requests = try? await control.pairRequests() else { return }+ receive(requests)+ if let blocked = try? await control.blocked(), blocked != self.blocked { self.blocked = blocked }+ }++ private func receive(_ requests: [PairRequest]) {+ let queue = PairingWatch.queue(requests)+ let arrived = PairingWatch.arrived(queue, announced: announcedRequests)+ PairingAlerts.shared.withdraw(PairingWatch.gone(queue, previous: pendingRequests))+ announcedRequests.formUnion(arrived.map(\.id))+ if queue != pendingRequests { pendingRequests = queue }+ for request in arrived {+ NSApp.requestUserAttention(.criticalRequest)+ Task { await PairingAlerts.shared.ask(about: request) }+ }+ }++ private func noticePairedByThemselves(_ sessions: [BrowserSession]) {+ let fresh = PairingWatch.pairedByThemselves(sessions, seen: seenPairings)+ seenPairings = Set(sessions.map(\.pairing))+ for session in fresh {+ say("\(session.displayName) connected to Browsentic Bridge by itself.")+ Task { await PairingAlerts.shared.announce(session) }+ }+ }++ func decide(_ request: PairRequest, allow: Bool, name: String? = nil) async {+ let named = name?.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty+ await onBridge("decide:\(request.id)") { control in+ try await control.decide(request.id, allow: allow, label: allow ? named : nil)+ PairingAlerts.shared.withdraw([request.id])+ self.pendingRequests.removeAll { $0.id == request.id }+ self.say(+ allow+ ? "\(named ?? request.name) can connect now."+ : "\(request.name) stays out. Reconnect it from the Browsers tab if you change your mind."+ )+ }+ await loadPairRequests()+ }++ /// An Allow or Deny pressed on a notification, which counts only while its request still waits with the same nonce.+ func answer(request id: String?, nonce: String?, allow: Bool) async {+ startPolling()+ await refresh()+ guard let id, let nonce, let request = PairingWatch.answerable(id, nonce: nonce, in: pendingRequests) else {+ return showMainWindow()+ }+ await decide(request, allow: allow)+ }++ func unpair(session id: String) async {+ startPolling()+ await refresh()+ await onBridge("revoke") { control in+ let count = try await control.revoke(session: id)+ self.say(count == 0 ? "That browser was already unpaired." : "Unpaired. It won’t reconnect by itself until you reconnect it.")+ }+ await refresh()+ }++ func reconnect(_ browser: BlockedBrowser) async {+ await onBridge("reconnect:\(browser.id)") { control in+ try await control.decide(browser.installId, allow: true)+ self.say("\(browser.name) can connect again. If it doesn’t by itself, press Reconnect in its Browsentic side panel.")+ }+ await refresh()+ }++ func rename(_ session: BrowserSession, to name: String) async {+ await onBridge("label:\(session.id)") { control in+ try await control.label(session: session.id, name.trimmingCharacters(in: .whitespacesAndNewlines))+ }+ await refresh()+ }++ func setPairingMode(_ mode: PairingMode) async {+ await onBridge("pairing") { control in self.pairingMode = try await control.pairing(set: mode).kind }+ }++ func showMainWindow(on tab: Tab? = nil) {+ startPolling()+ if let tab, phase == .main { self.tab = tab }+ if let openMainWindow {+ openMainWindow()+ } else if let mainWindow {+ mainWindow.makeKeyAndOrderFront(nil)+ } else {+ NSWorkspace.shared.open(Bundle.main.bundleURL)+ }+ NSApp.activate()+ }+func loadAgents() async {guard let cli else { return }if let state = try? await cli.agents() { agents = state }@@ -457,7 +580,15 @@ final class AppModel: ObservableObject {let result = try await cli.addExtension(to: row.id)if result.chosen?.opened != true, let url = URL(string: row.storeUrl) { self.open(url, in: row) }if let code = result.pairingCode, let expiresAt = result.expiresAt { self.pairing = PairingCode(code: code, expiresAt: expiresAt) }- self.say("\(row.steps.first ?? "") Then click Browsentic in \(row.label)’s toolbar and enter the code below.")+ self.say("\(row.steps.first ?? "") \(self.afterAdding(row))")+ }+ }++ private func afterAdding(_ row: BrowserRow) -> String {+ switch pairingMode {+ case .auto: "It connects by itself. If it asks for a code, use the one below."+ case .ask: "Allow it here when it asks to connect."+ default: "Then click Browsentic in \(row.label)’s toolbar and enter the code below."}}@@ -513,6 +644,7 @@ final class AppModel: ObservableObject {CommandLink.unlink()_ = try await cli.uninstall(keepSkills: keepSkills)self.poller?.cancel()+ self.poller = nilself.updateWatcher?.cancel()self.markOff()self.phase = .preflight@@ -581,6 +713,13 @@ final class AppModel: ObservableObject {do { try await work(cli, control) } catch { if !quiet { report(error) } }}+ private func onBridge(_ key: String, _ work: @escaping (ControlClient) async throws -> Void) async {+ guard !busy.contains(key) else { return }+ busy.insert(key)+ defer { busy.remove(key) }+ do { try await work(control) } catch { report(error) }+ }+func say(_ text: String) { show(Notice(text: text, isError: false)) }func report(_ error: Error) { show(Notice(text: error.localizedDescription, isError: true)) }@@ -596,3 +735,7 @@ final class AppModel: ObservableObject {try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))}}++extension String {+ var nilIfEmpty: String? { isEmpty ? nil : self }+}diff --git a/src/mac/Sources/Browsentic/App/BrowsenticApp.swift b/src/mac/Sources/Browsentic/App/BrowsenticApp.swiftindex d7e3c21..a96f030 100644--- a/src/mac/Sources/Browsentic/App/BrowsenticApp.swift+++ b/src/mac/Sources/Browsentic/App/BrowsenticApp.swift@@ -4,7 +4,7 @@ import SwiftUI@mainstruct BrowsenticApp: App {@NSApplicationDelegateAdaptor(AppDelegate.self) private var delegate- @StateObject private var model = AppModel()+ @StateObject private var model = AppModel.shared@AppStorage("appearance") private var appearance = Appearance.system.rawValueprivate var scheme: ColorScheme? { Appearance(rawValue: appearance)?.scheme }@@ -48,12 +48,22 @@ struct BrowsenticApp: App {MenuBarExtra {MenuBarContent().environmentObject(model)} label: {- Image(nsImage: model.daemon == .on ? MenuBarMark.on : MenuBarMark.off)+ Image(nsImage: model.pendingRequests.isEmpty ? (model.daemon == .on ? MenuBarMark.on : MenuBarMark.off) : MenuBarMark.asking)}}}final class AppDelegate: NSObject, NSApplicationDelegate {+ /// A notification that launches the app is delivered before launch finishes, so the delegate has to be in place first.+ func applicationWillFinishLaunching(_: Notification) {+ PairingAlerts.shared.install()+ }++ /// The Bridge starts the app with `--pairing`, in the background, when a browser asks and nobody is watching.+ func applicationDidFinishLaunching(_: Notification) {+ if CommandLine.arguments.contains("--pairing") { AppModel.shared.startPolling() }+ }+func applicationShouldTerminateAfterLastWindowClosed(_: NSApplication) -> Bool { false }func applicationShouldHandleReopen(_: NSApplication, hasVisibleWindows visible: Bool) -> Bool {@@ -64,6 +74,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {private struct RootView: View {@EnvironmentObject private var model: AppModel+ @Environment(\.openWindow) private var openWindowvar body: some View {ZStack(alignment: .bottom) {@@ -79,6 +90,10 @@ private struct RootView: View {}.frame(maxWidth: .infinity, maxHeight: .infinity).background { Backdrop() }+ .sheet(item: Binding(get: { model.pendingRequests.first }, set: { _ in })) { request in+ PairRequestSheet(request: request).environmentObject(model)+ }+ .onAppear { model.openMainWindow = { openWindow(id: "main") } }}}@@ -87,6 +102,13 @@ private struct MenuBarContent: View {@Environment(\.openWindow) private var openWindowvar body: some View {+ ForEach(model.pendingRequests) { request in+ Button("\(request.name) wants to connect…") {+ openWindow(id: "main")+ NSApp.activate()+ }+ }+ if !model.pendingRequests.isEmpty { Divider() }Text("Browsentic Bridge: \(model.daemon.label)\(model.status.map { " · 127.0.0.1:\($0.port)" } ?? "")")if let status = model.status {Text(status.connected ? "Extension connected" : "Extension not connected")diff --git a/src/mac/Sources/Browsentic/App/PairingAlerts.swift b/src/mac/Sources/Browsentic/App/PairingAlerts.swiftnew file mode 100644index 0000000..843210c--- /dev/null+++ b/src/mac/Sources/Browsentic/App/PairingAlerts.swift@@ -0,0 +1,113 @@+import AppKit+import UserNotifications++/// Pairing notifications. They are a convenience only: an ad-hoc signed build may never be allowed to+/// post, so the approval sheet, the menu bar dot and the Dock bounce carry the flow without them.+final class PairingAlerts: NSObject, UNUserNotificationCenterDelegate {+ static let shared = PairingAlerts()++ private enum Category {+ static let request = "PAIR_REQUEST"+ static let connected = "PAIR_CONNECTED"+ }++ private enum Action {+ static let allow = "ALLOW"+ static let deny = "DENY"+ static let unpair = "UNPAIR"+ }++ private enum Key {+ static let request = "request"+ static let nonce = "nonce"+ static let session = "session"+ }++ /// Outside an app bundle, as under `swift run` or `swift test`, the notification center traps.+ private var center: UNUserNotificationCenter? {+ Bundle.main.bundleURL.pathExtension == "app" ? .current() : nil+ }++ func install() {+ guard let center else { return }+ center.delegate = self+ center.setNotificationCategories([+ UNNotificationCategory(+ identifier: Category.request,+ actions: [+ UNNotificationAction(identifier: Action.allow, title: "Allow"),+ UNNotificationAction(identifier: Action.deny, title: "Deny", options: .destructive),+ ],+ intentIdentifiers: []+ ),+ UNNotificationCategory(+ identifier: Category.connected,+ actions: [UNNotificationAction(identifier: Action.unpair, title: "Unpair", options: .destructive)],+ intentIdentifiers: []+ ),+ ])+ }++ func ask(about request: PairRequest) async {+ let content = UNMutableNotificationContent()+ content.title = "\(request.name) wants to connect to Browsentic Bridge"+ content.subtitle = "\(SourceLabel.of(request.source).capitalizedFirst) · v\(request.extensionVersion)"+ content.body = "Allow it to use your agent and drive this browser?"+ content.categoryIdentifier = Category.request+ content.userInfo = [Key.request: request.id, Key.nonce: request.nonce]+ content.sound = .default+ await post(content, as: request.id)+ }++ func announce(_ session: BrowserSession) async {+ let content = UNMutableNotificationContent()+ content.title = "\(session.displayName) connected to Browsentic Bridge"+ content.body = "It paired by itself. If that wasn’t you, unpair it."+ content.categoryIdentifier = Category.connected+ content.userInfo = [Key.session: session.id]+ await post(content, as: "connected:\(session.pairing)")+ }++ func withdraw(_ requests: Set<String>) {+ guard let center, !requests.isEmpty else { return }+ center.removeDeliveredNotifications(withIdentifiers: Array(requests))+ center.removePendingNotificationRequests(withIdentifiers: Array(requests))+ }++ /// Asks for permission the first time there is something to say, never at launch.+ private func post(_ content: UNNotificationContent, as identifier: String) async {+ guard let center, await mayPost(center) else { return }+ try? await center.add(UNNotificationRequest(identifier: identifier, content: content, trigger: nil))+ }++ private func mayPost(_ center: UNUserNotificationCenter) async -> Bool {+ switch await center.notificationSettings().authorizationStatus {+ case .authorized, .provisional: true+ case .notDetermined: (try? await center.requestAuthorization(options: [.alert, .sound])) ?? false+ default: false+ }+ }++ func userNotificationCenter(_: UNUserNotificationCenter, willPresent _: UNNotification) async -> UNNotificationPresentationOptions {+ await AppModel.shared.mainWindowVisible ? [.list] : [.banner, .list, .sound]+ }++ func userNotificationCenter(_: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {+ let info = response.notification.request.content.userInfo+ let request = info[Key.request] as? String+ let nonce = info[Key.nonce] as? String+ let session = info[Key.session] as? String+ switch response.actionIdentifier {+ case Action.allow, Action.deny:+ await AppModel.shared.answer(request: request, nonce: nonce, allow: response.actionIdentifier == Action.allow)+ case Action.unpair:+ if let session { await AppModel.shared.unpair(session: session) }+ default:+ await AppModel.shared.showMainWindow(on: request == nil ? .browsers : nil)+ }+ }+}++extension String {+ var capitalizedFirst: String { prefix(1).uppercased() + dropFirst() }+}diff --git a/src/mac/Sources/Browsentic/Core/ControlClient.swift b/src/mac/Sources/Browsentic/Core/ControlClient.swiftindex 9f0ebda..9f1d2d8 100644--- a/src/mac/Sources/Browsentic/Core/ControlClient.swift+++ b/src/mac/Sources/Browsentic/Core/ControlClient.swift@@ -64,14 +64,55 @@ actor ControlClient {}func revoke(_ session: BrowserSession?) async throws -> Int {+ try await revoke(session: session?.sessionId, origin: session?.origin)+ }++ func revoke(session: String?, origin: String? = nil) async throws -> Int {var frame: [String: Any] = ["op": "revoke"]- if let session {- frame["origin"] = session.origin- if let id = session.sessionId { frame["session"] = id }- }+ if let origin { frame["origin"] = origin }+ if let session { frame["session"] = session }return try await request(frame, as: Reply<Int>.self, key: "revoked")}+ /// `watch` makes this socket an approver, sent `pair-requests-changed` whenever the list changes.+ func pairRequests(watch: Bool = true) async throws -> [PairRequest] {+ try await request(["op": "pairRequests", "watch": watch, "as": "app"], as: Reply<[PairRequest]>.self, key: "requests")+ }++ /// `request` is a request id, or an install id, which also lets a kept-out browser back in.+ func decide(_ request: String, allow: Bool, label: String? = nil) async throws {+ var frame: [String: Any] = ["op": "decide", "request": request, "allow": allow]+ if let label { frame["label"] = label }+ try await acknowledged(frame)+ }++ func pairing(set mode: PairingMode? = nil) async throws -> PairingSetting {+ var frame: [String: Any] = ["op": "pairing"]+ if let mode { frame["set"] = mode.rawValue }+ let setting = try await whole(frame, as: PairingSetting.self)+ if let error = setting.error { throw BridgeRefusal(message: error) }+ return setting+ }++ func blocked() async throws -> [BlockedBrowser] {+ try await request(["op": "blocked"], as: Reply<[BlockedBrowser]>.self, key: "blocked")+ }++ /// An empty label goes back to the browser's own name.+ func label(session: String, _ label: String) async throws {+ try await acknowledged(["op": "label", "session": session, "label": label])+ }++ private func acknowledged(_ frame: [String: Any]) async throws {+ let answer = try await whole(frame, as: Acknowledgement.self)+ if !answer.ok { throw BridgeRefusal(message: answer.error ?? "Browsentic Bridge said no.") }+ }++ private func whole<Value: Decodable>(_ frame: [String: Any], as _: Value.Type) async throws -> Value {+ let data = try await send(frame)+ do { return try JSONDecoder().decode(Value.self, from: data) } catch { throw ControlError.malformed }+ }+func agent(set: String? = nil, grant: String? = nil) async throws -> AgentState {var frame: [String: Any] = ["op": "agent"]if let set { frame["set"] = set }diff --git a/src/mac/Sources/Browsentic/Core/Models.swift b/src/mac/Sources/Browsentic/Core/Models.swiftindex e747eb1..67a8b5b 100644--- a/src/mac/Sources/Browsentic/Core/Models.swift+++ b/src/mac/Sources/Browsentic/Core/Models.swift@@ -16,6 +16,53 @@ struct BridgeStatus: Decodable, Equatable {let extensionVersion: String?let pairedBrowsers: Intlet pairingPending: Bool+ /// Absent from a Bridge before automatic pairing.+ let pairing: PairingSetting?+}++enum PairingMode: String, CaseIterable, Identifiable {+ case auto, ask, code++ var id: String { rawValue }++ var label: String {+ switch self {+ case .auto: "Automatic"+ case .ask: "Ask me"+ case .code: "Code only"+ }+ }++ var detail: String {+ switch self {+ case .auto: "A browser with Browsentic connects by itself."+ case .ask: "You allow each new browser here first."+ case .code: "A browser connects only with a code you type into it."+ }+ }++ var pairsByItself: Bool { self != .code }+}++/// The `pairing` answer, and the same pair inside `status`. The mode stays a string so a mode this app does not know yet still decodes.+struct PairingSetting: Decodable, Equatable {+ let mode: String+ let approver: String+ let error: String?++ var kind: PairingMode? { PairingMode(rawValue: mode) }+}++enum PairedBy: String {+ case code, auto, approved++ var label: String {+ switch self {+ case .auto: "Paired by itself"+ case .approved: "Allowed"+ case .code: "Paired with a code"+ }+ }}struct BrowserSession: Decodable, Identifiable, Equatable {@@ -29,14 +76,91 @@ struct BrowserSession: Decodable, Identifiable, Equatable {let pairedAt: Stringlet lastSeenAt: Stringlet connected: Bool+ let label: String?+ /// Absent from a Bridge before automatic pairing, when every browser paired with a code.+ let pairedBy: String?enum CodingKeys: String, CodingKey {case sessionId = "id"- case browser, origin, source, extensionVersion, pairedAt, lastSeenAt, connected+ case browser, origin, source, extensionVersion, pairedAt, lastSeenAt, connected, label, pairedBy}var id: String { sessionId ?? origin }var extensionId: String { origin.replacingOccurrences(of: #"^[a-z-]+-extension://"#, with: "", options: .regularExpression) }+ var name: String? { label ?? browser }+ var displayName: String { name ?? "This browser" }+ var paired: PairedBy { pairedBy.flatMap(PairedBy.init(rawValue:)) ?? .code }+ /// Changes when the same browser pairs again, so a second pairing counts as new.+ var pairing: String { "\(id)@\(pairedAt)" }+}++/// A browser waiting for someone to let it in, from `pairRequests`.+struct PairRequest: Decodable, Identifiable, Equatable {+ let id: String+ let installId: String+ let browser: String?+ let source: String+ let extensionVersion: String+ let firstAt: Double+ let lastAskAt: Double+ /// Minted by the Bridge per request and handed only to approvers, so an answer can prove which request it is for.+ let nonce: String++ var name: String { browser ?? "A browser" }+ var shortId: String { String(installId.prefix(8)) }+ var askedAt: Date { Date(timeIntervalSince1970: firstAt / 1000) }+}++/// A browser kept out after an Unpair or a Deny, until someone reconnects it.+struct BlockedBrowser: Decodable, Identifiable, Equatable {+ let installId: String+ let browser: String?+ let origin: String+ let at: String+ let reason: String++ var id: String { installId }+ var name: String { browser ?? "A browser" }+ var shortId: String { String(installId.prefix(8)) }+ var why: String { reason == "denied" ? "Denied" : "Unpaired" }+}++/// What the Bridge answers an op that only succeeds or fails.+struct Acknowledgement: Decodable {+ let ok: Bool+ let error: String?+}++struct BridgeRefusal: LocalizedError {+ let message: String+ var errorDescription: String? { message }+}++/// The pure decisions behind the approval sheet and the notifications, kept apart so they can be tested.+enum PairingWatch {+ /// Oldest first, so the sheet shows requests in the order browsers asked.+ static func queue(_ requests: [PairRequest]) -> [PairRequest] {+ requests.sorted { ($0.firstAt, $0.id) < ($1.firstAt, $1.id) }+ }++ static func arrived(_ requests: [PairRequest], announced: Set<String>) -> [PairRequest] {+ requests.filter { !announced.contains($0.id) }+ }++ static func gone(_ requests: [PairRequest], previous: [PairRequest]) -> Set<String> {+ Set(previous.map(\.id)).subtracting(requests.map(\.id))+ }++ /// Nil `seen` is the first look at a Bridge: everything already there is old news.+ static func pairedByThemselves(_ sessions: [BrowserSession], seen: Set<String>?) -> [BrowserSession] {+ guard let seen else { return [] }+ return sessions.filter { $0.paired == .auto && !seen.contains($0.pairing) }+ }++ /// An answer from a notification counts only for a request still waiting, with the nonce the Bridge gave it.+ static func answerable(_ id: String, nonce: String, in requests: [PairRequest]) -> PairRequest? {+ requests.first { $0.id == id && $0.nonce == nonce && !nonce.isEmpty }+ }}struct PairingCode: Decodable, Equatable {diff --git a/src/mac/Sources/Browsentic/Theme/MenuBarMark.swift b/src/mac/Sources/Browsentic/Theme/MenuBarMark.swiftindex ab113fd..09b1ff3 100644--- a/src/mac/Sources/Browsentic/Theme/MenuBarMark.swift+++ b/src/mac/Sources/Browsentic/Theme/MenuBarMark.swift@@ -1,11 +1,13 @@import AppKit-/// The brand mark for the menu bar, a template so macOS tints it for the bar. Its centre node is hollow while the Bridge is off.+/// The brand mark for the menu bar, a template so macOS tints it for the bar. Its centre node is hollow while the Bridge is off,+/// and a dot in the corner says a browser is waiting to be let in.enum MenuBarMark {static let on = draw(running: true)static let off = draw(running: false)+ static let asking = draw(running: true, asking: true)- private static func draw(running: Bool) -> NSImage {+ private static func draw(running: Bool, asking: Bool = false) -> NSImage {let image = NSImage(size: NSSize(width: 18, height: 18), flipped: true) { rect inguard let context = NSGraphicsContext.current?.cgContext else { return false }let unit = rect.width / 32@@ -42,6 +44,14 @@ enum MenuBarMark {context.setLineWidth(2 * unit)context.strokeEllipse(in: circle(x, y, r))}++ if asking {+ context.setBlendMode(.clear)+ context.fillEllipse(in: circle(26.5, 6.5, 7.5))+ context.setBlendMode(.normal)+ context.setFillColor(ink)+ context.fillEllipse(in: circle(26.5, 6.5, 5))+ }return true}image.isTemplate = truediff --git a/src/mac/Sources/Browsentic/Views/BrowsersView.swift b/src/mac/Sources/Browsentic/Views/BrowsersView.swiftindex cd19835..5860a83 100644--- a/src/mac/Sources/Browsentic/Views/BrowsersView.swift+++ b/src/mac/Sources/Browsentic/Views/BrowsersView.swift@@ -13,50 +13,152 @@ struct BrowsersView: View {Card {VStack(alignment: .leading, spacing: 14) {HStack {- SectionTitle(title: "Paired browsers", subtitle: "Each one holds a key of its own. Unpairing drops the key and disconnects it at once.")+ SectionTitle(title: "Paired browsers", subtitle: "Each one holds a key of its own. Unpairing drops the key, disconnects it at once and keeps it out until you reconnect it.")Spacer()if model.sessions.count > 1 {Button("Unpair all") { confirmingAll = true }.buttonStyle(QuietButtonStyle(tint: Palette.danger))}}if model.sessions.isEmpty {- EmptyState(icon: "globe", title: "No browser is paired", detail: "Add the extension from the Overview tab, or get a code above and enter it in the Browsentic side panel.")+ EmptyState(icon: "globe", title: "No browser is paired", detail: emptyDetail)} else {ForEach(model.sessions) { SessionRow(session: $0) }}}}+ if !model.blocked.isEmpty { KeptOutCard() }}}.confirmationDialog("Unpair every browser?", isPresented: $confirmingAll) {Button("Unpair all", role: .destructive) { Task { await model.revoke(nil) } }- } message: { Text("Each one will need a new pairing code to connect again.") }+ } message: { Text("They won’t reconnect by themselves until you reconnect them.") }+ }++ private var emptyDetail: String {+ switch model.pairingMode {+ case .auto: "Add the extension from the Overview tab and it connects by itself."+ case .ask: "Add the extension from the Overview tab, then allow it here when it asks to connect."+ default: "Add the extension from the Overview tab, or get a code above and enter it in the Browsentic side panel."+ }}}private struct SessionRow: View {@EnvironmentObject private var model: AppModellet session: BrowserSession+ @State private var confirming = false+ @State private var renaming = falsevar body: some View {HStack(spacing: 12) {GlowDot(color: session.connected ? Palette.lime : Palette.inkFaint, pulsing: session.connected)VStack(alignment: .leading, spacing: 3) {- if let browser = session.browser {- Text(browser).font(.system(size: 13, weight: .medium)).foregroundStyle(Palette.ink)+ if let name = session.name {+ HStack(spacing: 6) {+ Text(name).font(.system(size: 13, weight: .medium)).foregroundStyle(Palette.ink)+ if let browser = session.browser, session.label != nil, browser != name {+ Text(browser).font(.system(size: 12)).foregroundStyle(Palette.inkFaint)+ }+ }+ }+ if !session.extensionId.isEmpty {+ Text(session.extensionId).font(.code(12)).foregroundStyle(session.name == nil ? Palette.ink : Palette.inkDim).textSelection(.enabled)}- Text(session.extensionId).font(.code(12)).foregroundStyle(session.browser == nil ? Palette.ink : Palette.inkDim).textSelection(.enabled)- Text("\(SourceLabel.of(session.source)) · v\(session.extensionVersion) · paired \(Timestamp.ago(session.pairedAt)) · seen \(Timestamp.ago(session.lastSeenAt))")+ Text("\(session.paired.label) \(Timestamp.ago(session.pairedAt)) · \(SourceLabel.of(session.source)) · v\(session.extensionVersion) · seen \(Timestamp.ago(session.lastSeenAt))").font(.system(size: 11.5)).foregroundStyle(Palette.inkDim)}Spacer()Pill(text: session.connected ? "Connected" : "Away", tint: session.connected ? Palette.lime : Palette.inkDim)- Button("Unpair") { Task { await model.revoke(session) } }+ if model.bridgePairs, session.sessionId != nil {+ Button("Rename") { renaming = true }+ .buttonStyle(QuietButtonStyle())+ .disabled(model.busy.contains("label:\(session.id)"))+ }+ Button("Unpair") { confirming = true }.buttonStyle(QuietButtonStyle(tint: Palette.danger)).disabled(model.busy.contains("revoke"))}.padding(12).background(Palette.ground2, in: RoundedRectangle(cornerRadius: 12, style: .continuous))+ .confirmationDialog("Unpair \(session.displayName)?", isPresented: $confirming) {+ Button("Unpair", role: .destructive) { Task { await model.revoke(session) } }+ } message: { Text("It won’t reconnect by itself until you reconnect it.") }+ .sheet(isPresented: $renaming) { RenameSheet(session: session).environmentObject(model) }+ }+}++private struct RenameSheet: View {+ @EnvironmentObject private var model: AppModel+ @Environment(\.dismiss) private var dismiss+ let session: BrowserSession+ @State private var name: String++ init(session: BrowserSession) {+ self.session = session+ _name = State(initialValue: session.name ?? "")+ }++ var body: some View {+ VStack(alignment: .leading, spacing: 14) {+ Text("Rename \(session.displayName)").font(.display(18)).foregroundStyle(Palette.ink)+ Text("A name of your own tells two profiles of one browser apart. Leave it empty to go back to \(session.browser ?? "the browser’s own name").")+ .font(.system(size: 12.5))+ .foregroundStyle(Palette.inkDim)+ .fixedSize(horizontal: false, vertical: true)+ TextField("Name", text: $name, prompt: Text(session.browser ?? "Name"))+ .textFieldStyle(.roundedBorder)+ .labelsHidden()+ .onSubmit(save)+ HStack {+ Spacer()+ Button("Cancel") { dismiss() }.buttonStyle(QuietButtonStyle())+ Button("Save", action: save).buttonStyle(PrimaryButtonStyle()).keyboardShortcut(.defaultAction)+ }+ }+ .padding(24)+ .frame(width: 420)+ .background(Palette.ground)+ }++ private func save() {+ dismiss()+ Task { await model.rename(session, to: name) }+ }+}++private struct KeptOutCard: View {+ @EnvironmentObject private var model: AppModel++ var body: some View {+ Card {+ VStack(alignment: .leading, spacing: 14) {+ SectionTitle(title: "Kept out", subtitle: "Browsers you unpaired or denied. They won’t connect by themselves until you reconnect them.")+ ForEach(model.blocked) { BlockedRow(browser: $0) }+ }+ }+ }+}++private struct BlockedRow: View {+ @EnvironmentObject private var model: AppModel+ let browser: BlockedBrowser++ var body: some View {+ HStack(spacing: 12) {+ Image(systemName: "hand.raised.fill").font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.inkFaint).frame(width: 8)+ VStack(alignment: .leading, spacing: 3) {+ Text(browser.name).font(.system(size: 13, weight: .medium)).foregroundStyle(Palette.ink)+ Text("\(browser.why) \(Timestamp.ago(browser.at)) · install \(browser.shortId)")+ .font(.system(size: 11.5))+ .foregroundStyle(Palette.inkDim)+ }+ Spacer()+ Button("Reconnect") { Task { await model.reconnect(browser) } }+ .buttonStyle(QuietButtonStyle(tint: Palette.brand))+ .disabled(model.busy.contains("reconnect:\(browser.id)"))+ }+ .padding(12)+ .background(Palette.ground2, in: RoundedRectangle(cornerRadius: 12, style: .continuous))}}diff --git a/src/mac/Sources/Browsentic/Views/OverviewView.swift b/src/mac/Sources/Browsentic/Views/OverviewView.swiftindex 36e3c89..6558c67 100644--- a/src/mac/Sources/Browsentic/Views/OverviewView.swift+++ b/src/mac/Sources/Browsentic/Views/OverviewView.swift@@ -83,11 +83,19 @@ struct OverviewView: View {case .on:model.status?.connected == true? "Open the side panel in your browser and say what you want. This window can close — Browsentic Bridge keeps running."- : "Browsentic Bridge is running. Add the extension to your browser below and pair it once, and the side panel comes alive."+ : "Browsentic Bridge is running. \(addAndConnect)"case .off: "Turn it on and the side panel in your browser can reach the agent you already run."case .starting, .stopping: "One moment."}}++ private var addAndConnect: String {+ switch model.pairingMode {+ case .auto: "Add the extension to your browser below and it connects by itself."+ case .ask: "Add the extension to your browser below and allow it here when it asks to connect."+ default: "Add the extension to your browser below and pair it once, and the side panel comes alive."+ }+ }}private struct PowerOrb: View {@@ -174,21 +182,38 @@ struct ConnectCard: View {var body: some View {Card {- VStack(alignment: .leading, spacing: 16) {- SectionTitle(- title: "Pair a browser",- subtitle: "Click Browsentic in your browser’s toolbar (the puzzle piece lists it), enter the code, and press Connect. It works once and expires in ten minutes."- )- if let pairing = model.pairing {- PairingCodeView(pairing: pairing)- } else {- Button { Task { await model.newPairingCode() } } label: { Label("Get a pairing code", systemImage: "key.horizontal") }- .buttonStyle(PrimaryButtonStyle())- .disabled(model.busy.contains("pair"))+ if let mode = model.pairingMode, mode.pairsByItself, model.pairing == nil {+ HStack(spacing: 16) {+ SectionTitle(title: "Connect a browser", subtitle: note(mode))+ Spacer(minLength: 0)+ codeButton.buttonStyle(QuietButtonStyle())+ }+ } else {+ VStack(alignment: .leading, spacing: 16) {+ SectionTitle(+ title: "Pair a browser",+ subtitle: "Click Browsentic in your browser’s toolbar (the puzzle piece lists it), enter the code, and press Connect. It works once and expires in ten minutes."+ )+ if let pairing = model.pairing {+ PairingCodeView(pairing: pairing)+ } else {+ codeButton.buttonStyle(PrimaryButtonStyle())+ }}}}}++ private var codeButton: some View {+ Button { Task { await model.newPairingCode() } } label: { Label("Get a pairing code", systemImage: "key.horizontal") }+ .disabled(model.busy.contains("pair"))+ }++ private func note(_ mode: PairingMode) -> String {+ mode == .ask+ ? "Browsers with Browsentic connect by themselves once you allow them here. Need a code instead?"+ : "Browsers with Browsentic connect by themselves. Need a code instead?"+ }}struct PairingCodeView: View {@@ -253,9 +278,12 @@ struct ExtensionCard: View {private var unpacked: Bool { showUnpacked ?? (model.stamp != nil) }private var subtitle: String {- model.sessions.contains(where: \.connected)- ? "In your browser and talking to Browsentic Bridge. Store copies update themselves."- : "Add it from your browser’s store, then click Browsentic in the toolbar and enter the pairing code once."+ if model.sessions.contains(where: \.connected) { return "In your browser and talking to Browsentic Bridge. Store copies update themselves." }+ switch model.pairingMode {+ case .auto: return "Add it from your browser’s store and it connects to Browsentic Bridge by itself."+ case .ask: return "Add it from your browser’s store, then allow it here when it asks to connect."+ default: return "Add it from your browser’s store, then click Browsentic in the toolbar and enter the pairing code once."+ }}}diff --git a/src/mac/Sources/Browsentic/Views/PairRequestSheet.swift b/src/mac/Sources/Browsentic/Views/PairRequestSheet.swiftnew file mode 100644index 0000000..0585afc--- /dev/null+++ b/src/mac/Sources/Browsentic/Views/PairRequestSheet.swift@@ -0,0 +1,92 @@+import SwiftUI++/// The one place a pairing request can always be answered, whatever happened to the notification.+struct PairRequestSheet: View {+ @EnvironmentObject private var model: AppModel+ let request: PairRequest+ @State private var name: String++ init(request: PairRequest) {+ self.request = request+ _name = State(initialValue: request.browser ?? "")+ }++ private var deciding: Bool { model.busy.contains("decide:\(request.id)") }+ private var waitingAfter: Int { max(0, model.pendingRequests.count - 1) }++ var body: some View {+ VStack(alignment: .leading, spacing: 18) {+ HStack(alignment: .top, spacing: 14) {+ Image(systemName: "puzzlepiece.extension.fill")+ .font(.system(size: 19, weight: .semibold))+ .foregroundStyle(Palette.brand)+ .frame(width: 44, height: 44)+ .background(Palette.brand.opacity(0.13), in: RoundedRectangle(cornerRadius: 12, style: .continuous))+ VStack(alignment: .leading, spacing: 6) {+ Text("\(request.name) wants to connect to Browsentic Bridge")+ .font(.display(17))+ .foregroundStyle(Palette.ink)+ .fixedSize(horizontal: false, vertical: true)+ Text("Allow it to use your agent and drive this browser? If you didn’t just install or open Browsentic in \(request.browser ?? "a browser"), don’t allow it.")+ .font(.system(size: 12.5))+ .foregroundStyle(Palette.inkDim)+ .fixedSize(horizontal: false, vertical: true)+ }+ }++ Grid(alignment: .leading, horizontalSpacing: 18, verticalSpacing: 7) {+ DetailRow(label: "From", value: SourceLabel.of(request.source).capitalizedFirst)+ DetailRow(label: "Version", value: "v\(request.extensionVersion)")+ DetailRow(label: "Install", value: request.shortId, code: true)+ DetailRow(label: "Asked", value: Timestamp.ago(request.askedAt))+ }+ .padding(14)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(Palette.ground2, in: RoundedRectangle(cornerRadius: 12, style: .continuous))+ .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(Palette.line))++ VStack(alignment: .leading, spacing: 6) {+ Text("Name").font(.system(size: 11.5, weight: .semibold)).foregroundStyle(Palette.inkDim)+ TextField("Name", text: $name, prompt: Text(request.name))+ .textFieldStyle(.roundedBorder)+ .labelsHidden()+ Text("Tells two profiles of one browser apart in the Browsers tab.")+ .font(.system(size: 11))+ .foregroundStyle(Palette.inkFaint)+ }++ HStack(spacing: 10) {+ if waitingAfter > 0 {+ Text("\(waitingAfter) more waiting").font(.system(size: 11.5)).foregroundStyle(Palette.inkDim)+ }+ Spacer()+ Button("Deny") { Task { await model.decide(request, allow: false) } }+ .buttonStyle(QuietButtonStyle(tint: Palette.danger))+ Button("Allow") { Task { await model.decide(request, allow: true, name: name) } }+ .buttonStyle(PrimaryButtonStyle())+ .keyboardShortcut(.defaultAction)+ }+ .disabled(deciding)+ }+ .padding(24)+ .frame(width: 470)+ .background(Palette.ground)+ .interactiveDismissDisabled()+ }+}++private struct DetailRow: View {+ let label: String+ let value: String+ var code = false++ var body: some View {+ GridRow {+ Text(label).font(.system(size: 11.5)).foregroundStyle(Palette.inkFaint)+ Text(value)+ .font(code ? .code(11.5) : .system(size: 12, weight: .medium))+ .foregroundStyle(Palette.ink)+ .textSelection(.enabled)+ }+ }+}diff --git a/src/mac/Sources/Browsentic/Views/SettingsView.swift b/src/mac/Sources/Browsentic/Views/SettingsView.swiftindex 970d8f1..1acefc3 100644--- a/src/mac/Sources/Browsentic/Views/SettingsView.swift+++ b/src/mac/Sources/Browsentic/Views/SettingsView.swift@@ -31,6 +31,8 @@ struct SettingsView: View {}}+ PairingCard()+BrowserSettings()Card {@@ -105,6 +107,63 @@ struct SettingsView: View {}}+private struct PairingCard: View {+ @EnvironmentObject private var model: AppModel++ var body: some View {+ Card {+ VStack(alignment: .leading, spacing: 14) {+ SectionTitle(title: "Pairing", subtitle: subtitle)+ VStack(spacing: 6) {+ ForEach(PairingMode.allCases) { mode in+ PairingOption(mode: mode, selected: model.pairingMode == mode) {+ Task { await model.setPairingMode(mode) }+ }+ }+ }+ .disabled(model.pairingMode == nil || model.busy.contains("pairing"))+ }+ }+ }++ private var subtitle: String {+ if model.daemon != .on { return "Turn Browsentic Bridge on to choose how browsers connect to it." }+ if model.status != nil, !model.bridgePairs { return "Restart Browsentic Bridge to choose how browsers connect to it." }+ return "How a browser with Browsentic connects to Browsentic Bridge on this Mac."+ }+}++private struct PairingOption: View {+ let mode: PairingMode+ let selected: Bool+ let choose: () -> Void+ @Environment(\.isEnabled) private var enabled++ var body: some View {+ let shape = RoundedRectangle(cornerRadius: 11, style: .continuous)+ Button(action: choose) {+ HStack(spacing: 12) {+ Image(systemName: selected ? "largecircle.fill.circle" : "circle")+ .font(.system(size: 14))+ .foregroundStyle(selected ? Palette.brand : Palette.inkFaint)+ VStack(alignment: .leading, spacing: 2) {+ Text(mode.label).font(.system(size: 13, weight: .medium)).foregroundStyle(Palette.ink)+ Text(mode.detail).font(.system(size: 11.5)).foregroundStyle(Palette.inkDim)+ }+ Spacer(minLength: 0)+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 9)+ .background(selected ? Palette.brand.opacity(0.1) : Palette.ground2, in: shape)+ .overlay(shape.strokeBorder(selected ? Palette.brand.opacity(0.45) : Palette.line))+ .opacity(enabled ? 1 : 0.55)+ .contentShape(shape)+ }+ .buttonStyle(.plain)+ .accessibilityAddTraits(selected ? .isSelected : [])+ }+}+private struct SwitchRow: View {let title: Stringlet subtitle: Stringdiff --git a/src/mac/Tests/BrowsenticTests/ModelTests.swift b/src/mac/Tests/BrowsenticTests/ModelTests.swiftindex 8e96ad2..bb59e46 100644--- a/src/mac/Tests/BrowsenticTests/ModelTests.swift+++ b/src/mac/Tests/BrowsenticTests/ModelTests.swift@@ -237,3 +237,150 @@ import Testing#expect(Tab.allCases.compactMap(\.badge) == ["Experimental"])}}++@Suite struct PairingDecodingTests {+ private func decode<Value: Decodable>(_ type: Value.Type, _ json: String) throws -> Value {+ try JSONDecoder().decode(type, from: Data(json.utf8))+ }++ @Test func statusFromABridgeBeforeAutomaticPairingHasNoMode() throws {+ let status = try decode(BridgeStatus.self, #"{"connected":true,"daemonVersion":"0.8.9","protocolVersion":22,"port":8765,"manifestInSync":true,"pairedBrowsers":1,"pairingPending":false}"#)+ #expect(status.pairing == nil)+ }++ @Test func statusSaysHowBrowsersPairAndWhoAllowsThem() throws {+ let status = try decode(BridgeStatus.self, #"{"connected":true,"daemonVersion":"0.9.0","protocolVersion":23,"port":8765,"manifestInSync":true,"connectedBrowsers":1,"pairedBrowsers":1,"pairingPending":false,"pairing":{"mode":"ask","approver":"app"}}"#)+ #expect(status.pairing?.kind == .ask)+ #expect(status.pairing?.approver == "app")+ }++ @Test func aModeThisAppDoesNotKnowYetStillDecodes() throws {+ let setting = try decode(PairingSetting.self, #"{"id":"1","op":"pairing","mode":"later","approver":"terminal"}"#)+ #expect(setting.kind == nil)+ #expect(setting.error == nil)+ }++ @Test func aRefusedModeChangeCarriesTheBridgesReason() throws {+ let setting = try decode(PairingSetting.self, #"{"id":"1","op":"pairing","mode":"auto","approver":"app","error":"An agent run cannot change how browsers pair."}"#)+ #expect(setting.kind == .auto)+ #expect(setting.error == "An agent run cannot change how browsers pair.")+ }++ @Test func sessionsFromABridgeBeforeAutomaticPairingReadAsPairedWithACode() throws {+ let session = try decode(BrowserSession.self, #"{"id":"i1","browser":"Chrome","origin":"chrome-extension://abc","source":"chrome-web-store","extensionVersion":"0.8.9","pairedAt":"2026-10-01T10:00:00.000Z","lastSeenAt":"2026-10-01T10:00:00.000Z","connected":true}"#)+ #expect(session.label == nil)+ #expect(session.paired == .code)+ #expect(session.paired.label == "Paired with a code")+ #expect(session.displayName == "Chrome")+ }++ @Test func aNamedSessionGoesByItsName() throws {+ let session = try decode(BrowserSession.self, #"{"id":"i1","browser":"Chrome","origin":"chrome-extension://abc","extensionVersion":"0.9.0","pairedAt":"2026-10-01T10:00:00.000Z","lastSeenAt":"2026-10-01T10:00:00.000Z","connected":false,"label":"Work Chrome","pairedBy":"auto"}"#)+ #expect(session.name == "Work Chrome")+ #expect(session.paired.label == "Paired by itself")+ #expect(session.pairing == "i1@2026-10-01T10:00:00.000Z")+ }++ @Test func aSessionWithNoBrowserOrNameStillHasSomethingToCallIt() throws {+ let session = try decode(BrowserSession.self, #"{"origin":"chrome-extension://abc","extensionVersion":"0.5.0","pairedAt":"2026-09-01T10:00:00.000Z","lastSeenAt":"2026-09-01T10:00:00.000Z","connected":true,"pairedBy":"approved"}"#)+ #expect(session.name == nil)+ #expect(session.displayName == "This browser")+ #expect(session.paired.label == "Allowed")+ }++ @Test func pairRequestsSayWhoIsAskingAndWhen() throws {+ let requests = try decode([PairRequest].self, #"""+ [{"id":"r1","installId":"0123456789abcdef","browser":"Brave","source":"chrome-web-store","extensionVersion":"0.9.0","firstAt":1790000000000,"lastAskAt":1790000005000,"nonce":"n1"},+ {"id":"r2","installId":"fedcba9876543210","source":"unpacked","extensionVersion":"0.9.0","firstAt":1790000001000,"lastAskAt":1790000001000,"nonce":"n2"}]+ """#)+ #expect(requests[0].name == "Brave")+ #expect(requests[0].shortId == "01234567")+ #expect(requests[0].askedAt == Date(timeIntervalSince1970: 1_790_000_000))+ #expect(requests[1].name == "A browser")+ #expect(SourceLabel.of(requests[1].source).capitalizedFirst == "Unpacked")+ }++ @Test func keptOutBrowsersSayWhy() throws {+ let blocked = try decode([BlockedBrowser].self, #"""+ [{"installId":"0123456789abcdef","browser":"Edge","origin":"chrome-extension://x","at":"2026-10-16T09:00:00.000Z","reason":"revoked"},+ {"installId":"fedcba9876543210","origin":"moz-extension://","at":"2026-10-16T09:00:00.000Z","reason":"denied"}]+ """#)+ #expect(blocked.map(\.why) == ["Unpaired", "Denied"])+ #expect(blocked.map(\.name) == ["Edge", "A browser"])+ #expect(blocked[1].id == "fedcba9876543210")+ #expect(Timestamp.date(blocked[0].at) != nil)+ }++ @Test func anOpThatOnlySucceedsOrFailsCarriesItsError() throws {+ #expect(try decode(Acknowledgement.self, #"{"id":"1","op":"decide","ok":true}"#).ok)+ let refused = try decode(Acknowledgement.self, #"{"id":"1","op":"decide","ok":false,"error":"No request or blocked browser has that id."}"#)+ #expect(!refused.ok)+ #expect(BridgeRefusal(message: refused.error ?? "").localizedDescription == "No request or blocked browser has that id.")+ }++ @Test func everyModeIsOneTheBridgeKnowsWithItsOwnLine() {+ #expect(PairingMode.allCases.map(\.rawValue) == ["auto", "ask", "code"])+ #expect(PairingMode.allCases.map(\.label) == ["Automatic", "Ask me", "Code only"])+ #expect(PairingMode.allCases.map(\.detail) == [+ "A browser with Browsentic connects by itself.",+ "You allow each new browser here first.",+ "A browser connects only with a code you type into it.",+ ])+ #expect(PairingMode.allCases.filter(\.pairsByItself) == [.auto, .ask])+ }+}++@Suite struct PairingWatchTests {+ private func request(_ id: String, at firstAt: Double, nonce: String = "nonce") -> PairRequest {+ PairRequest(id: id, installId: "install-\(id)", browser: "Chrome", source: "chrome-web-store", extensionVersion: "0.9.0", firstAt: firstAt, lastAskAt: firstAt, nonce: nonce)+ }++ private func session(_ id: String, pairedBy: String?, at pairedAt: String = "2026-10-16T09:00:00.000Z") -> BrowserSession {+ BrowserSession(sessionId: id, browser: "Chrome", origin: "chrome-extension://\(id)", source: "chrome-web-store", extensionVersion: "0.9.0", pairedAt: pairedAt, lastSeenAt: pairedAt, connected: true, label: nil, pairedBy: pairedBy)+ }++ @Test func theQueueShowsTheOldestRequestFirst() {+ let queue = PairingWatch.queue([request("b", at: 2), request("c", at: 3), request("a", at: 1)])+ #expect(queue.map(\.id) == ["a", "b", "c"])+ }++ @Test func eachRequestIsAnnouncedOnce() {+ let requests = [request("a", at: 1), request("b", at: 2)]+ #expect(PairingWatch.arrived(requests, announced: []).map(\.id) == ["a", "b"])+ #expect(PairingWatch.arrived(requests, announced: ["a"]).map(\.id) == ["b"])+ #expect(PairingWatch.arrived(requests, announced: ["a", "b"]).isEmpty)+ }++ @Test func aDecidedOrExpiredRequestIsGone() {+ let before = [request("a", at: 1), request("b", at: 2)]+ #expect(PairingWatch.gone([request("b", at: 2)], previous: before) == ["a"])+ #expect(PairingWatch.gone(before, previous: before).isEmpty)+ #expect(PairingWatch.gone([], previous: before) == ["a", "b"])+ }++ @Test func browsersAlreadyThereOnTheFirstLookAreNotNews() {+ let sessions = [session("one", pairedBy: "auto")]+ #expect(PairingWatch.pairedByThemselves(sessions, seen: nil).isEmpty)+ }++ @Test func onlyABrowserThatPairedByItselfIsAnnounced() {+ let sessions = [session("auto", pairedBy: "auto"), session("allowed", pairedBy: "approved"), session("code", pairedBy: "code"), session("old", pairedBy: nil)]+ #expect(PairingWatch.pairedByThemselves(sessions, seen: []).map(\.id) == ["auto"])+ #expect(PairingWatch.pairedByThemselves(sessions, seen: Set(sessions.map(\.pairing))).isEmpty)+ }++ @Test func theSameBrowserPairingAgainIsAnnouncedAgain() {+ let first = session("one", pairedBy: "auto", at: "2026-10-16T09:00:00.000Z")+ let again = session("one", pairedBy: "auto", at: "2026-10-16T10:00:00.000Z")+ #expect(PairingWatch.pairedByThemselves([again], seen: [first.pairing]).map(\.id) == ["one"])+ }++ @Test func aNotificationAnswerCountsOnlyWithTheRequestsOwnNonce() {+ let waiting = [request("a", at: 1, nonce: "secret")]+ #expect(PairingWatch.answerable("a", nonce: "secret", in: waiting)?.id == "a")+ #expect(PairingWatch.answerable("a", nonce: "guess", in: waiting) == nil)+ #expect(PairingWatch.answerable("b", nonce: "secret", in: waiting) == nil)+ #expect(PairingWatch.answerable("a", nonce: "secret", in: []) == nil)+ #expect(PairingWatch.answerable("a", nonce: "", in: [request("a", at: 1, nonce: "")]) == nil)+ }+}