Skip to content

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.

feat(mac): the app shows a browser's finished monitor, task or reminder as a macOS notification while the browser is behind, tells the Bridge whether macOS lets it notify, and a click hands the front to that browser and brings it back to the tab

Shahriarce840340d465
diff --git a/docs/internals/mac-app.md b/docs/internals/mac-app.md
index 49b4547..ec33694 100644
--- a/docs/internals/mac-app.md
+++ b/docs/internals/mac-app.md
@@ -39,6 +39,16 @@ notifications; the sheet, the dot and the bounce carry the flow without them. Wh
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.
+## Browser notices
+
+When a monitor, a scheduled task or a timer finishes while its browser is out of sight, the Bridge
+hands the notice to the app, which posts it as a macOS notification (`BROWSER_NOTICE`, identifier
+`notice:<id>`, so a repeat replaces it). On every socket to a Bridge at protocol 24 or later the app
+sends `notices {watch, allowed}`, and again whenever notification permission changes (checked on the
+poll and on activation), so the browser keeps its own card when the app cannot post. On
+`notices-changed` it calls `takeNotices`. A click yields activation to the browser it came from
+(`BrowserApps`, brand to bundle ids) and sends `openNotice`, leaving this window alone.
+
## The payload
[build-app.sh](../../src/mac/Scripts/build-app.sh) stages `Contents/Resources/payload/` in the npm
diff --git a/src/mac/Sources/Browsentic/App/AppModel.swift b/src/mac/Sources/Browsentic/App/AppModel.swift
index fe6be87..a5fa057 100644
--- a/src/mac/Sources/Browsentic/App/AppModel.swift
+++ b/src/mac/Sources/Browsentic/App/AppModel.swift
@@ -1,4 +1,5 @@
import AppKit
+import os
import SwiftUI
enum Phase { case preflight, main }
@@ -107,6 +108,8 @@ final class AppModel: ObservableObject {
private var watchingAndroid = false
private var announcedRequests: Set<String> = []
private var seenPairings: Set<String>?
+ /// What this socket was last told about notification permission; nil until it is told.
+ private var noticesReported: Bool?
var cli: CLI? { node.map(CLI.init) }
var appVersion: String { Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? Payload.bundledVersion ?? "dev" }
@@ -270,6 +273,8 @@ final class AppModel: ObservableObject {
await self?.loadAndroid()
case "pair-requests-changed":
await self?.loadPairRequests()
+ case "notices-changed":
+ await self?.takeNotices()
default:
break
}
@@ -288,6 +293,7 @@ final class AppModel: ObservableObject {
func refresh() async {
guard let lock = Self.readLock() else { return markOff() }
if await control.connect(lock) {
+ noticesReported = nil
Task { await self.loadPreferences(watch: true) }
if watchingAndroid { Task { await self.watchAndroid(true) } }
}
@@ -306,6 +312,7 @@ final class AppModel: ObservableObject {
stamp = ExtensionFiles.stamp()
if changed { Task { await loadBrowsers() } }
if status.pairing != nil { await loadPairRequests() }
+ await reportNotices()
} catch {
await control.close()
markOff()
@@ -323,6 +330,7 @@ final class AppModel: ObservableObject {
pairingMode = nil
blocked = []
seenPairings = nil
+ noticesReported = nil
PairingAlerts.shared.withdraw(Set(pendingRequests.map(\.id)))
pendingRequests = []
}
@@ -454,6 +462,42 @@ final class AppModel: ObservableObject {
await onBridge("pairing") { control in self.pairingMode = try await control.pairing(set: mode).kind }
}
+ // MARK: Browser notices
+
+ /// Tells the Bridge whether this app can show a browser's notices, again only when that changes.
+ func reportNotices() async {
+ guard NoticeWatch.supported(by: status) else { return }
+ let allowed = await PairingAlerts.shared.mayNotify()
+ guard NoticeWatch.needsReport(allowed: allowed, reported: noticesReported),
+ (try? await control.notices(allowed: allowed)) != nil
+ else { return }
+ noticesReported = allowed
+ if allowed { await takeNotices() }
+ }
+
+ func takeNotices() async {
+ guard let notices = try? await control.takeNotices() else { return }
+ for notice in notices { await PairingAlerts.shared.show(notice) }
+ }
+
+ /// The browser brings the notice's tab to the front; this app's window stays where it is. A click makes
+ /// this app active, and since macOS 14 another app comes forward only when the active one yields to it.
+ func openNotice(_ id: String, from browser: String?) async {
+ let running = Set(NSWorkspace.shared.runningApplications.compactMap(\.bundleIdentifier))
+ if let app = BrowserApps.running(for: browser, among: running) {
+ NSApp.yieldActivation(toApplicationWithBundleIdentifier: app)
+ }
+ if status == nil {
+ startPolling()
+ await refresh()
+ }
+ do {
+ try await control.openNotice(id)
+ } catch {
+ Self.log.notice("openNotice \(id, privacy: .public) from \(browser ?? "an unnamed browser", privacy: .public) was not delivered: \(error.localizedDescription, privacy: .public)")
+ }
+ }
+
func showMainWindow(on tab: Tab? = nil) {
startPolling()
if let tab, phase == .main { self.tab = tab }
@@ -731,6 +775,8 @@ final class AppModel: ObservableObject {
}
}
+ private static let log = Logger(subsystem: Bundle.main.bundleIdentifier ?? "com.imshaikot.browsentic", category: "notices")
+
private static func pause(_ seconds: Double) async {
try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
}
diff --git a/src/mac/Sources/Browsentic/App/BrowsenticApp.swift b/src/mac/Sources/Browsentic/App/BrowsenticApp.swift
index a96f030..c0b6758 100644
--- a/src/mac/Sources/Browsentic/App/BrowsenticApp.swift
+++ b/src/mac/Sources/Browsentic/App/BrowsenticApp.swift
@@ -64,6 +64,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
if CommandLine.arguments.contains("--pairing") { AppModel.shared.startPolling() }
}
+ /// Notification permission can change in System Settings while the app is away.
+ func applicationDidBecomeActive(_: Notification) {
+ Task { await AppModel.shared.reportNotices() }
+ }
+
func applicationShouldTerminateAfterLastWindowClosed(_: NSApplication) -> Bool { false }
func applicationShouldHandleReopen(_: NSApplication, hasVisibleWindows visible: Bool) -> Bool {
diff --git a/src/mac/Sources/Browsentic/App/PairingAlerts.swift b/src/mac/Sources/Browsentic/App/PairingAlerts.swift
index 5d2a433..96740f1 100644
--- a/src/mac/Sources/Browsentic/App/PairingAlerts.swift
+++ b/src/mac/Sources/Browsentic/App/PairingAlerts.swift
@@ -1,14 +1,16 @@
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.
+/// The app's notifications: pairing, and the notices a browser hands over while it is out of sight.
+/// Pairing ones 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 that 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"
+ static let notice = "BROWSER_NOTICE"
}
private enum Action {
@@ -21,8 +23,12 @@ final class PairingAlerts: NSObject, UNUserNotificationCenterDelegate {
static let request = "request"
static let nonce = "nonce"
static let session = "session"
+ static let notice = "notice"
+ static let browser = "browser"
}
+ @MainActor private var askedForPermission = false
+
/// 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
@@ -45,6 +51,7 @@ final class PairingAlerts: NSObject, UNUserNotificationCenterDelegate {
actions: [UNNotificationAction(identifier: Action.unpair, title: "Unpair", options: .destructive)],
intentIdentifiers: []
),
+ UNNotificationCategory(identifier: Category.notice, actions: [], intentIdentifiers: []),
])
}
@@ -68,6 +75,29 @@ final class PairingAlerts: NSObject, UNUserNotificationCenterDelegate {
await post(content, as: "connected:\(session.pairing)")
}
+ func show(_ notice: QueuedNotice) async {
+ let content = UNMutableNotificationContent()
+ content.title = notice.title
+ if let browser = notice.browser { content.subtitle = browser }
+ content.body = notice.body
+ content.categoryIdentifier = Category.notice
+ content.threadIdentifier = Category.notice
+ var info = [Key.notice: notice.id]
+ info[Key.browser] = notice.browser
+ content.userInfo = info
+ content.sound = .default
+ await post(content, as: NoticeWatch.identifier(for: notice.id))
+ }
+
+ /// Whether the app can post right now, asking once if nobody has decided yet. Never true outside an app bundle.
+ @MainActor func mayNotify() async -> Bool {
+ guard let center else { return false }
+ let status = await center.notificationSettings().authorizationStatus
+ guard status == .notDetermined, !askedForPermission else { return NoticeWatch.allows(status) }
+ askedForPermission = true
+ return (try? await center.requestAuthorization(options: [.alert, .sound])) ?? false
+ }
+
func withdraw(_ requests: Set<String>) {
guard let center, !requests.isEmpty else { return }
center.removeDeliveredNotifications(withIdentifiers: Array(requests))
@@ -88,8 +118,10 @@ final class PairingAlerts: NSObject, UNUserNotificationCenterDelegate {
}
}
- func userNotificationCenter(_: UNUserNotificationCenter, willPresent _: UNNotification) async -> UNNotificationPresentationOptions {
- await AppModel.shared.mainWindowVisible ? [.list] : [.banner, .list, .sound]
+ /// A browser notice shows even over this app: whoever reads it is not in the browser.
+ func userNotificationCenter(_: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
+ if notification.request.content.categoryIdentifier == Category.notice { return [.banner, .list, .sound] }
+ return await AppModel.shared.mainWindowVisible ? [.list] : [.banner, .list, .sound]
}
func userNotificationCenter(_: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
@@ -97,6 +129,12 @@ final class PairingAlerts: NSObject, UNUserNotificationCenterDelegate {
let request = info[Key.request] as? String
let nonce = info[Key.nonce] as? String
let session = info[Key.session] as? String
+ if let notice = info[Key.notice] as? String {
+ if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
+ await AppModel.shared.openNotice(notice, from: info[Key.browser] as? String)
+ }
+ return
+ }
switch response.actionIdentifier {
case Action.allow, Action.deny:
await AppModel.shared.answer(request: request, nonce: nonce, allow: response.actionIdentifier == Action.allow)
diff --git a/src/mac/Sources/Browsentic/Core/ControlClient.swift b/src/mac/Sources/Browsentic/Core/ControlClient.swift
index 9f1d2d8..7fdafe7 100644
--- a/src/mac/Sources/Browsentic/Core/ControlClient.swift
+++ b/src/mac/Sources/Browsentic/Core/ControlClient.swift
@@ -103,6 +103,21 @@ actor ControlClient {
try await acknowledged(["op": "label", "session": session, "label": label])
}
+ /// Makes this socket the one that shows browser notices; `allowed` says whether this Mac lets the app post them.
+ func notices(allowed: Bool) async throws {
+ try await acknowledged(["op": "notices", "watch": true, "allowed": allowed])
+ }
+
+ /// Hands over every notice waiting to be shown; the Bridge forgets them.
+ func takeNotices() async throws -> [QueuedNotice] {
+ try await request(["op": "takeNotices"], as: Reply<LossyList<QueuedNotice>>.self, key: "notices").items
+ }
+
+ /// The browser the notice came from brings its tab to the front.
+ func openNotice(_ notice: String) async throws {
+ try await acknowledged(["op": "openNotice", "notice": notice])
+ }
+
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.") }
diff --git a/src/mac/Sources/Browsentic/Core/Models.swift b/src/mac/Sources/Browsentic/Core/Models.swift
index 67a8b5b..498e289 100644
--- a/src/mac/Sources/Browsentic/Core/Models.swift
+++ b/src/mac/Sources/Browsentic/Core/Models.swift
@@ -1,4 +1,5 @@
import Foundation
+import UserNotifications
struct Lockfile: Decodable, Equatable {
let pid: Int
@@ -125,6 +126,76 @@ struct BlockedBrowser: Decodable, Identifiable, Equatable {
var why: String { reason == "denied" ? "Denied" : "Unpaired" }
}
+/// A monitor, task or timer that finished while its browser was out of sight, handed over by the Bridge.
+/// `kind` and `tone` stay strings so a value this app does not know yet never drops the notice.
+struct QueuedNotice: Decodable, Identifiable, Equatable {
+ let id: String
+ let kind: String?
+ let title: String
+ let body: String
+ let tone: String?
+ let browser: String?
+}
+
+/// Decodes every element it can and skips the rest, so one malformed entry never costs the others.
+struct LossyList<Element: Decodable>: Decodable {
+ let items: [Element]
+
+ private struct Skipped: Decodable {
+ init(from _: Decoder) {}
+ }
+
+ init(from decoder: Decoder) throws {
+ var container = try decoder.unkeyedContainer()
+ var items: [Element] = []
+ while !container.isAtEnd {
+ if let item = try? container.decode(Element.self) { items.append(item) } else { _ = try container.decode(Skipped.self) }
+ }
+ self.items = items
+ }
+}
+
+enum NoticeWatch {
+ /// The first Bridge protocol with `notices`, `takeNotices` and `openNotice`; an older Bridge never answers them.
+ static let protocolVersion = 24
+
+ static func supported(by status: BridgeStatus?) -> Bool { (status?.protocolVersion ?? 0) >= protocolVersion }
+
+ static func allows(_ status: UNAuthorizationStatus) -> Bool { status == .authorized || status == .provisional }
+
+ /// Nil `reported` is a socket that has not been told yet.
+ static func needsReport(allowed: Bool, reported: Bool?) -> Bool { reported != allowed }
+
+ /// A repeat of the same event replaces the notification instead of stacking another.
+ static func identifier(for notice: String) -> String { "notice:\(notice)" }
+}
+
+/// The apps behind each brand a browser reports, every channel of one browser sharing its brand, so a notice
+/// click can let the browser it came from take the front.
+enum BrowserApps {
+ static let bundleIds: [String: [String]] = [
+ "Google Chrome": ["com.google.Chrome", "com.google.Chrome.beta", "com.google.Chrome.dev", "com.google.Chrome.canary"],
+ "Chromium": ["org.chromium.Chromium"],
+ "Microsoft Edge": ["com.microsoft.edgemac", "com.microsoft.edgemac.Beta", "com.microsoft.edgemac.Dev", "com.microsoft.edgemac.Canary"],
+ "Brave": ["com.brave.Browser", "com.brave.Browser.beta", "com.brave.Browser.nightly"],
+ "Opera": ["com.operasoftware.Opera"],
+ "Opera GX": ["com.operasoftware.OperaGX"],
+ "Vivaldi": ["com.vivaldi.Vivaldi"],
+ "Arc": ["company.thebrowser.Browser"],
+ "Firefox": ["org.mozilla.firefox", "org.mozilla.firefoxdeveloperedition", "org.mozilla.nightly"],
+ ]
+
+ static func candidates(for brand: String?) -> [String] {
+ guard let brand else { return [] }
+ return bundleIds.first { $0.key.caseInsensitiveCompare(brand) == .orderedSame }?.value ?? []
+ }
+
+ /// The running app the notice came from; an unknown brand, or none of its apps running, names nothing.
+ static func running(for brand: String?, among running: Set<String>) -> String? {
+ candidates(for: brand).first(where: running.contains)
+ }
+}
+
/// What the Bridge answers an op that only succeeds or fails.
struct Acknowledgement: Decodable {
let ok: Bool
diff --git a/src/mac/Tests/BrowsenticTests/ModelTests.swift b/src/mac/Tests/BrowsenticTests/ModelTests.swift
index bb59e46..b3ba5c0 100644
--- a/src/mac/Tests/BrowsenticTests/ModelTests.swift
+++ b/src/mac/Tests/BrowsenticTests/ModelTests.swift
@@ -384,3 +384,97 @@ import Testing
#expect(PairingWatch.answerable("a", nonce: "", in: [request("a", at: 1, nonce: "")]) == nil)
}
}
+
+@Suite struct NoticeTests {
+ private func decode<Value: Decodable>(_ type: Value.Type, _ json: String) throws -> Value {
+ try JSONDecoder().decode(type, from: Data(json.utf8))
+ }
+
+ private func status(protocolVersion: Int) throws -> BridgeStatus {
+ try decode(BridgeStatus.self, #"{"connected":true,"daemonVersion":"0.9.0","protocolVersion":\#(protocolVersion),"port":8765,"manifestInSync":true,"pairedBrowsers":1,"pairingPending":false}"#)
+ }
+
+ @Test func aNoticeCarriesWhatTheNotificationShows() throws {
+ let notice = try decode(QueuedNotice.self, #"{"id":"monitor:42:3","kind":"monitor","title":"Price dropped","body":"The jacket is now $80.","tone":"live","browser":"Work Chrome","at":1790000000000}"#)
+ #expect(notice.title == "Price dropped")
+ #expect(notice.body == "The jacket is now $80.")
+ #expect(notice.browser == "Work Chrome")
+ #expect(notice.kind == "monitor" && notice.tone == "live")
+ }
+
+ @Test func aKindOrToneThisAppDoesNotKnowKeepsTheNotice() throws {
+ let notice = try decode(QueuedNotice.self, #"{"id":"n1","kind":"reminder","title":"T","body":"B","tone":"loud","at":1}"#)
+ #expect(notice.kind == "reminder" && notice.tone == "loud")
+ let bare = try decode(QueuedNotice.self, #"{"id":"n2","title":"T","body":"B"}"#)
+ #expect(bare.kind == nil && bare.tone == nil && bare.browser == nil)
+ }
+
+ @Test func oneMalformedNoticeNeverCostsTheOthers() throws {
+ let list = try decode(LossyList<QueuedNotice>.self, #"""
+ [{"id":"a","kind":"task","title":"Done","body":"x","tone":"warn","at":1},
+ {"kind":"timer","body":"no id or title"},
+ "not even an object",
+ {"id":"b","kind":"timer","title":"Time's up","body":"y","tone":"live","at":2}]
+ """#)
+ #expect(list.items.map(\.id) == ["a", "b"])
+ #expect(try decode(LossyList<QueuedNotice>.self, "[]").items.isEmpty)
+ }
+
+ @Test func onlyABridgeThatKnowsNoticesIsAskedAboutThem() throws {
+ #expect(!NoticeWatch.supported(by: nil))
+ #expect(!NoticeWatch.supported(by: try status(protocolVersion: 23)))
+ #expect(NoticeWatch.supported(by: try status(protocolVersion: 24)))
+ #expect(NoticeWatch.supported(by: try status(protocolVersion: 25)))
+ }
+
+ @Test func theBridgeHearsAboutPermissionOnANewSocketAndWhenItChanges() {
+ #expect(NoticeWatch.needsReport(allowed: false, reported: nil))
+ #expect(NoticeWatch.needsReport(allowed: true, reported: nil))
+ #expect(!NoticeWatch.needsReport(allowed: true, reported: true))
+ #expect(!NoticeWatch.needsReport(allowed: false, reported: false))
+ #expect(NoticeWatch.needsReport(allowed: true, reported: false))
+ #expect(NoticeWatch.needsReport(allowed: false, reported: true))
+ }
+
+ @Test func onlyAGrantedPermissionLetsTheAppShowNotices() {
+ #expect(NoticeWatch.allows(.authorized))
+ #expect(NoticeWatch.allows(.provisional))
+ #expect(!NoticeWatch.allows(.denied))
+ #expect(!NoticeWatch.allows(.notDetermined))
+ }
+
+ @Test func aRepeatOfTheSameEventReplacesItsNotification() {
+ #expect(NoticeWatch.identifier(for: "monitor:42:3") == "notice:monitor:42:3")
+ #expect(NoticeWatch.identifier(for: "monitor:42:3") == NoticeWatch.identifier(for: "monitor:42:3"))
+ #expect(NoticeWatch.identifier(for: "a") != "a")
+ }
+}
+
+@Suite struct BrowserAppsTests {
+ @Test func everyBrandTheExtensionReportsNamesItsApps() {
+ let brands = ["Google Chrome", "Chromium", "Microsoft Edge", "Brave", "Opera", "Vivaldi", "Arc", "Firefox"]
+ #expect(brands.allSatisfy { !BrowserApps.candidates(for: $0).isEmpty })
+ #expect(BrowserApps.candidates(for: "Google Chrome").first == "com.google.Chrome")
+ #expect(BrowserApps.candidates(for: "Microsoft Edge").first == "com.microsoft.edgemac")
+ #expect(BrowserApps.candidates(for: "Arc") == ["company.thebrowser.Browser"])
+ #expect(BrowserApps.candidates(for: "Firefox").first == "org.mozilla.firefox")
+ }
+
+ @Test func noBundleIdBelongsToTwoBrands() {
+ let ids = BrowserApps.bundleIds.values.flatMap { $0 }
+ #expect(Set(ids).count == ids.count)
+ }
+
+ @Test func theRunningChannelIsTheOneThatComesForward() {
+ #expect(BrowserApps.running(for: "Google Chrome", among: ["com.google.Chrome.canary", "com.apple.Safari"]) == "com.google.Chrome.canary")
+ #expect(BrowserApps.running(for: "Google Chrome", among: ["com.google.Chrome", "com.google.Chrome.beta"]) == "com.google.Chrome")
+ #expect(BrowserApps.running(for: "microsoft edge", among: ["com.microsoft.edgemac.Dev"]) == "com.microsoft.edgemac.Dev")
+ }
+
+ @Test func anUnknownBrandOrABrowserNotRunningYieldsToNothing() {
+ #expect(BrowserApps.running(for: "Netscape", among: ["com.google.Chrome"]) == nil)
+ #expect(BrowserApps.running(for: nil, among: ["com.google.Chrome"]) == nil)
+ #expect(BrowserApps.running(for: "chrome-extension://abc", among: ["com.google.Chrome"]) == nil)
+ #expect(BrowserApps.running(for: "Brave", among: ["com.google.Chrome"]) == nil)
+ }
+}