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): native control client, Node runtime installer and payload installer

Shahriard8474dfb8e63
diff --git a/src/mac/Package.swift b/src/mac/Package.swift
new file mode 100644
index 0000000..ded1b1e
--- /dev/null
+++ b/src/mac/Package.swift
@@ -0,0 +1,20 @@
+// swift-tools-version: 5.9
+import PackageDescription
+
+let package = Package(
+ name: "Browsentic",
+ platforms: [.macOS(.v14)],
+ targets: [
+ .executableTarget(
+ name: "Browsentic",
+ path: "Sources/Browsentic",
+ swiftSettings: [.unsafeFlags(["-parse-as-library"])]
+ ),
+ .testTarget(
+ name: "BrowsenticTests",
+ dependencies: ["Browsentic"],
+ path: "Tests/BrowsenticTests"
+ ),
+ ],
+ swiftLanguageVersions: [.v5]
+)
diff --git a/src/mac/Sources/Browsentic/Core/CLI.swift b/src/mac/Sources/Browsentic/Core/CLI.swift
new file mode 100644
index 0000000..18d2fa1
--- /dev/null
+++ b/src/mac/Sources/Browsentic/Core/CLI.swift
@@ -0,0 +1,53 @@
+import Foundation
+
+enum CLIError: LocalizedError {
+ case failed(String)
+ case unreadable(String)
+
+ var errorDescription: String? {
+ switch self {
+ case .failed(let detail): detail.isEmpty ? "The browsentic command exited with an error — see the Logs tab." : detail
+ case .unreadable(let command): "“browsentic \(command)” printed something this app cannot read — update the app."
+ }
+ }
+}
+
+/// Everything the control socket does not carry goes through the installed command, so the app
+/// and a terminal can never disagree about what an operation does.
+struct CLI {
+ let node: NodeInstall
+
+ @discardableResult
+ func run(_ arguments: [String], timeout: TimeInterval = 90) async throws -> String {
+ let result = await Shell.run(node.path, [Paths.cliEntry.path] + arguments, extraPath: [node.binDir], timeout: timeout)
+ guard result.ok else { throw CLIError.failed(result.failure) }
+ return result.stdout
+ }
+
+ func json<Value: Decodable>(_ arguments: [String], as _: Value.Type, timeout: TimeInterval = 90) async throws -> Value {
+ let output = try await run(arguments + ["--json"], timeout: timeout)
+ guard let start = output.firstIndex(where: { $0 == "{" || $0 == "[" }),
+ let value = try? JSONDecoder().decode(Value.self, from: Data(output[start...].utf8))
+ else { throw CLIError.unreadable(arguments.joined(separator: " ")) }
+ return value
+ }
+
+ func start() async throws { try await run(["start"]) }
+ func stop() async throws { try await run(["stop"]) }
+ func restart() async throws { try await run(["restart"]) }
+
+ func installExtension(force: Bool = false) async throws -> SetupResult {
+ try await json(["setup", "--no-pair", "--no-self-update"] + (force ? ["--force"] : []), as: SetupResult.self)
+ }
+
+ func agents() async throws -> AgentState { try await json(["agent"], as: AgentState.self) }
+ func setModel(_ model: String?, for kind: String) async throws { try await run(["agent", "model", kind] + (model.map { [$0] } ?? [])) }
+ func skills() async throws -> SkillListing { try await json(["skills"], as: SkillListing.self) }
+ func approvals() async throws -> [Grant] { try await json(["approvals"], as: GrantListing.self).grants }
+ func clearApprovals(host: String?) async throws { try await run(["approvals", "clear"] + (host.map { [$0] } ?? [])) }
+ func downloads() async throws -> DownloadListing { try await json(["downloads"], as: DownloadListing.self) }
+ func clearDownloads() async throws { try await run(["downloads", "clear"]) }
+ func uninstall(keepSkills: Bool) async throws -> String {
+ try await run(["uninstall", "--yes"] + (keepSkills ? ["--keep-skills"] : []), timeout: 60)
+ }
+}
diff --git a/src/mac/Sources/Browsentic/Core/ControlClient.swift b/src/mac/Sources/Browsentic/Core/ControlClient.swift
new file mode 100644
index 0000000..85209ac
--- /dev/null
+++ b/src/mac/Sources/Browsentic/Core/ControlClient.swift
@@ -0,0 +1,153 @@
+import Foundation
+
+enum ControlError: LocalizedError {
+ case offline
+ case timeout
+ case malformed
+
+ var errorDescription: String? {
+ switch self {
+ case .offline: "The daemon is not running — turn it on from the Overview tab."
+ case .timeout: "The daemon did not answer in time — restart it from the Overview tab."
+ case .malformed: "The daemon answered with something this app cannot read — update the app."
+ }
+ }
+}
+
+/// The daemon's `/control` socket, spoken natively: the same frames RemoteBridge sends, with the
+/// bearer token from the lockfile. Holding it open is also what keeps the daemon from idling out.
+actor ControlClient {
+ private var task: URLSessionWebSocketTask?
+ private var pending: [String: CheckedContinuation<Data, Error>] = [:]
+ private(set) var lock: Lockfile?
+
+ var isOpen: Bool { task?.state == .running }
+
+ func connect(_ lock: Lockfile) {
+ if self.lock == lock, isOpen { return }
+ close()
+ var request = URLRequest(url: URL(string: "ws://127.0.0.1:\(lock.port)/control")!)
+ request.setValue("Bearer \(lock.token)", forHTTPHeaderField: "Authorization")
+ request.timeoutInterval = 5
+ let task = URLSession.shared.webSocketTask(with: request)
+ self.task = task
+ self.lock = lock
+ task.resume()
+ listen(on: task)
+ }
+
+ func close() {
+ task?.cancel(with: .normalClosure, reason: nil)
+ task = nil
+ lock = nil
+ failAll(ControlError.offline)
+ }
+
+ func status() async throws -> BridgeStatus {
+ try await request(["op": "status"], as: Reply<BridgeStatus>.self, key: "status")
+ }
+
+ func sessions() async throws -> [BrowserSession] {
+ try await request(["op": "sessions"], as: Reply<[BrowserSession]>.self, key: "sessions")
+ }
+
+ func pair() async throws -> PairingCode {
+ let data = try await send(["op": "pair"])
+ return try JSONDecoder().decode(PairingCode.self, from: data)
+ }
+
+ func revoke(origin: String?) async throws -> Int {
+ var frame: [String: Any] = ["op": "revoke"]
+ if let origin { frame["origin"] = origin }
+ return try await request(frame, as: Reply<Int>.self, key: "revoked")
+ }
+
+ func agent(set: String? = nil, grant: String? = nil) async throws -> AgentState {
+ var frame: [String: Any] = ["op": "agent"]
+ if let set { frame["set"] = set }
+ if let grant { frame["grant"] = grant }
+ return try await request(frame, as: Reply<AgentState>.self, key: "state", timeout: 60)
+ }
+
+ private struct Reply<Value: Decodable>: Decodable {
+ let value: Value
+
+ init(from decoder: Decoder) throws {
+ let key = decoder.userInfo[Self.keyInfo] as? String ?? ""
+ let container = try decoder.container(keyedBy: AnyKey.self)
+ value = try container.decode(Value.self, forKey: AnyKey(key))
+ }
+
+ static var keyInfo: CodingUserInfoKey { CodingUserInfoKey(rawValue: "replyKey")! }
+ }
+
+ private struct AnyKey: CodingKey {
+ let stringValue: String
+ var intValue: Int? { nil }
+ init(_ value: String) { stringValue = value }
+ init?(stringValue: String) { self.stringValue = stringValue }
+ init?(intValue: Int) { nil }
+ }
+
+ private func request<Value: Decodable>(
+ _ frame: [String: Any], as _: Reply<Value>.Type, key: String, timeout: TimeInterval = 10
+ ) async throws -> Value {
+ let data = try await send(frame, timeout: timeout)
+ let decoder = JSONDecoder()
+ decoder.userInfo[Reply<Value>.keyInfo] = key
+ do { return try decoder.decode(Reply<Value>.self, from: data).value } catch { throw ControlError.malformed }
+ }
+
+ private func send(_ frame: [String: Any], timeout: TimeInterval = 10) async throws -> Data {
+ guard let task, isOpen else { throw ControlError.offline }
+ let id = UUID().uuidString
+ var framed = frame
+ framed["id"] = id
+ let text = String(data: try JSONSerialization.data(withJSONObject: framed), encoding: .utf8)!
+
+ return try await withCheckedThrowingContinuation { continuation in
+ pending[id] = continuation
+ task.send(.string(text)) { [weak self] error in
+ guard let error else { return }
+ Task { await self?.settle(id, .failure(error)) }
+ }
+ Task { [weak self] in
+ try? await Task.sleep(nanoseconds: UInt64(timeout * 1_000_000_000))
+ await self?.settle(id, .failure(ControlError.timeout))
+ }
+ }
+ }
+
+ private func settle(_ id: String, _ result: Result<Data, Error>) {
+ pending.removeValue(forKey: id)?.resume(with: result)
+ }
+
+ private func failAll(_ error: Error) {
+ let waiting = pending
+ pending.removeAll()
+ waiting.values.forEach { $0.resume(throwing: error) }
+ }
+
+ private func listen(on task: URLSessionWebSocketTask) {
+ task.receive { [weak self] result in
+ Task { await self?.received(result, on: task) }
+ }
+ }
+
+ private func received(_ result: Result<URLSessionWebSocketTask.Message, Error>, on task: URLSessionWebSocketTask) {
+ guard task === self.task else { return }
+ switch result {
+ case .failure:
+ self.task = nil
+ lock = nil
+ failAll(ControlError.offline)
+ case .success(let message):
+ if case .string(let text) = message, let data = text.data(using: .utf8),
+ let frame = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let id = frame["id"] as? String {
+ settle(id, .success(data))
+ }
+ listen(on: task)
+ }
+ }
+}
diff --git a/src/mac/Sources/Browsentic/Core/Models.swift b/src/mac/Sources/Browsentic/Core/Models.swift
new file mode 100644
index 0000000..d3ad062
--- /dev/null
+++ b/src/mac/Sources/Browsentic/Core/Models.swift
@@ -0,0 +1,181 @@
+import Foundation
+
+struct Lockfile: Decodable, Equatable {
+ let pid: Int
+ let port: Int
+ let token: String
+ let daemonVersion: String?
+}
+
+struct BridgeStatus: Decodable, Equatable {
+ let connected: Bool
+ let daemonVersion: String
+ let protocolVersion: Int
+ let port: Int
+ let manifestInSync: Bool
+ let extensionVersion: String?
+ let pairedBrowsers: Int
+ let pairingPending: Bool
+}
+
+struct BrowserSession: Decodable, Identifiable, Equatable {
+ let origin: String
+ let extensionVersion: String
+ let pairedAt: String
+ let lastSeenAt: String
+ let connected: Bool
+
+ var id: String { origin }
+ var extensionId: String { origin.replacingOccurrences(of: "chrome-extension://", with: "") }
+}
+
+struct PairingCode: Decodable, Equatable {
+ let code: String
+ let expiresAt: Double
+
+ var expiry: Date { Date(timeIntervalSince1970: expiresAt / 1000) }
+ var grouped: String { code.count > 4 ? "\(code.prefix(4))-\(code.dropFirst(4))" : code }
+}
+
+struct AgentProblem: Decodable, Equatable {
+ let code: String
+ let message: String
+ let fix: String?
+ let grantable: Bool?
+}
+
+struct RunnerStatus: Decodable, Identifiable, Equatable {
+ let kind: String
+ let bin: String
+ let ready: Bool
+ let version: String?
+ let model: String?
+ let problem: AgentProblem?
+
+ var id: String { kind }
+}
+
+struct AgentDescriptor: Decodable, Identifiable, Equatable {
+ let kind: String
+ let label: String
+ let vendor: String
+ let bin: String
+ let install: String
+ let docs: String
+ let models: [String]
+
+ var id: String { kind }
+ var installsWithNpm: Bool { install.hasPrefix("npm ") }
+}
+
+struct AgentState: Decodable, Equatable {
+ let active: String
+ let runners: [RunnerStatus]
+ var catalog: [AgentDescriptor]?
+}
+
+struct Skill: Decodable, Identifiable, Equatable {
+ let name: String
+ let description: String
+ let triggers: [String]
+ let isDefault: Bool
+ let category: String
+ let domains: [String]
+ let source: String
+ let provenance: String
+ let path: String?
+
+ var id: String { "\(source)/\(name)" }
+}
+
+struct AgentSkill: Decodable, Identifiable, Equatable {
+ let name: String
+ let description: String?
+ var id: String { name }
+}
+
+struct SkillListing: Decodable, Equatable {
+ let skills: [Skill]
+ let dirs: [String]
+ let agent: String
+ let agentSkills: [AgentSkill]
+}
+
+struct Grant: Decodable, Identifiable, Equatable {
+ let action: String
+ let host: String
+ let at: String
+ var id: String { "\(action)@\(host)" }
+}
+
+struct GrantListing: Decodable { let grants: [Grant] }
+
+struct DownloadRecord: Decodable, Identifiable, Equatable {
+ let id: String
+ let name: String
+ let mime: String
+ let size: Int
+ let url: String
+ let host: String?
+ let notes: String
+ let savedTo: String
+ let capturedAt: String
+}
+
+struct DownloadListing: Decodable, Equatable {
+ let dir: String
+ let downloads: [DownloadRecord]
+}
+
+struct SetupResult: Decodable {
+ struct Daemon: Decodable { let port: Int; let pid: Int }
+ let version: String
+ let extensionDir: String
+ let daemon: Daemon
+ let alreadyPaired: Bool
+ let pairingCode: String?
+}
+
+struct InstallStamp: Decodable, Equatable {
+ let version: String
+ let installedAt: String
+}
+
+enum Timestamp {
+ private static let parser: ISO8601DateFormatter = {
+ let formatter = ISO8601DateFormatter()
+ formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ return formatter
+ }()
+ private static let relative: RelativeDateTimeFormatter = {
+ let formatter = RelativeDateTimeFormatter()
+ formatter.unitsStyle = .full
+ return formatter
+ }()
+
+ static func date(_ text: String) -> Date? { parser.date(from: text) }
+
+ static func ago(_ text: String, now: Date = Date()) -> String {
+ guard let date = date(text) else { return text }
+ if now.timeIntervalSince(date) < 5 { return "just now" }
+ return relative.localizedString(for: date, relativeTo: now)
+ }
+}
+
+enum Version {
+ static func isNewer(_ candidate: String, than current: String) -> Bool {
+ let release: (String) -> [Int] = { version in
+ version.split(separator: "-")[0].split(separator: ".").map { Int($0) ?? 0 }
+ }
+ let a = release(candidate), b = release(current)
+ for index in 0..<3 {
+ let left = index < a.count ? a[index] : 0, right = index < b.count ? b[index] : 0
+ if left != right { return left > right }
+ }
+ return false
+ }
+
+ static func major(_ version: String) -> Int {
+ Int(version.trimmingCharacters(in: CharacterSet(charactersIn: "v \n")).split(separator: ".").first ?? "") ?? 0
+ }
+}
diff --git a/src/mac/Sources/Browsentic/Core/NodeRuntime.swift b/src/mac/Sources/Browsentic/Core/NodeRuntime.swift
new file mode 100644
index 0000000..487e915
--- /dev/null
+++ b/src/mac/Sources/Browsentic/Core/NodeRuntime.swift
@@ -0,0 +1,158 @@
+import CryptoKit
+import Foundation
+
+struct NodeInstall: Equatable {
+ let path: String
+ let version: String
+ let isPrivate: Bool
+
+ var binDir: String { (path as NSString).deletingLastPathComponent }
+ var npm: String { "\(binDir)/npm" }
+}
+
+enum NodeRuntimeError: LocalizedError {
+ case noRelease
+ case checksum
+ case unpack(String)
+
+ var errorDescription: String? {
+ switch self {
+ case .noRelease: "nodejs.org did not list a release for this Mac — check the connection and try again."
+ case .checksum: "The Node.js download did not match its published checksum, so it was discarded — try again."
+ case .unpack(let detail): "Node.js downloaded but would not unpack: \(detail)"
+ }
+ }
+}
+
+enum NodeRuntime {
+ static let minimumMajor = 20
+
+ /// The user's own Node when it is new enough, otherwise the private copy under ~/.browsentic/runtime.
+ static func locate() async -> NodeInstall? {
+ let candidates = [(Shell.which("node"), false), (Paths.privateNode.path, true)]
+ for (path, isPrivate) in candidates {
+ guard let path, FileManager.default.isExecutableFile(atPath: path) else { continue }
+ let result = await Shell.run(path, ["--version"], timeout: 8)
+ let version = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
+ if result.ok, Version.major(version) >= minimumMajor {
+ return NodeInstall(path: path, version: version, isPrivate: isPrivate)
+ }
+ }
+ return nil
+ }
+
+ static var architecture: String {
+ var info = utsname()
+ uname(&info)
+ let machine = withUnsafeBytes(of: &info.machine) { String(decoding: $0.prefix { $0 != 0 }, as: UTF8.self) }
+ return machine == "arm64" ? "arm64" : "x64"
+ }
+
+ private struct Release: Decodable {
+ let version: String
+ let files: [String]
+ let lts: LTS
+
+ enum LTS: Decodable {
+ case name(String), none
+ init(from decoder: Decoder) throws {
+ self = (try? decoder.singleValueContainer().decode(String.self)).map(LTS.name) ?? .none
+ }
+ }
+ }
+
+ /// Downloads the current LTS from nodejs.org into ~/.browsentic/runtime/node. No sudo, no
+ /// package manager, and nothing outside ~/.browsentic is touched.
+ static func installPrivate(progress: @escaping @Sendable (Double, String) -> Void) async throws -> NodeInstall {
+ progress(0, "Finding the current Node.js LTS")
+ let (index, _) = try await URLSession.shared.data(from: URL(string: "https://nodejs.org/dist/index.json")!)
+ let platform = architecture == "arm64" ? "osx-arm64-tar" : "osx-x64-tar"
+ let releases = try JSONDecoder().decode([Release].self, from: index)
+ guard let release = releases.first(where: {
+ if case .name = $0.lts { return $0.files.contains(platform) }
+ return false
+ }) else { throw NodeRuntimeError.noRelease }
+
+ let name = "node-\(release.version)-darwin-\(architecture).tar.gz"
+ let base = URL(string: "https://nodejs.org/dist/\(release.version)/")!
+
+ let (sums, _) = try await URLSession.shared.data(from: base.appendingPathComponent("SHASUMS256.txt"))
+ let expected = String(decoding: sums, as: UTF8.self)
+ .split(whereSeparator: \.isNewline)
+ .first { $0.hasSuffix(" \(name)") }?
+ .split(separator: " ").first.map(String.init)
+ guard let expected else { throw NodeRuntimeError.noRelease }
+
+ progress(0.02, "Downloading Node.js \(release.version)")
+ let archive = try await Downloader().download(base.appendingPathComponent(name)) { fraction in
+ progress(0.02 + fraction * 0.88, "Downloading Node.js \(release.version)")
+ }
+ defer { try? FileManager.default.removeItem(at: archive) }
+
+ progress(0.92, "Verifying the download")
+ let digest = SHA256.hash(data: try Data(contentsOf: archive, options: .mappedIfSafe))
+ guard digest.map({ String(format: "%02x", $0) }).joined() == expected else { throw NodeRuntimeError.checksum }
+
+ progress(0.95, "Unpacking")
+ let files = FileManager.default
+ let staging = Paths.runtime.appendingPathComponent("node.tmp-\(ProcessInfo.processInfo.processIdentifier)")
+ let target = Paths.runtime.appendingPathComponent("node")
+ try? files.removeItem(at: staging)
+ try files.createDirectory(at: staging, withIntermediateDirectories: true)
+ let unpacked = await Shell.run("/usr/bin/tar", ["-xzf", archive.path, "-C", staging.path, "--strip-components", "1"])
+ guard unpacked.ok else {
+ try? files.removeItem(at: staging)
+ throw NodeRuntimeError.unpack(unpacked.failure)
+ }
+ try? files.removeItem(at: target)
+ try files.moveItem(at: staging, to: target)
+
+ progress(1, "Node.js \(release.version) is ready")
+ return NodeInstall(path: Paths.privateNode.path, version: release.version, isPrivate: true)
+ }
+}
+
+private final class Downloader: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
+ private var continuation: CheckedContinuation<URL, Error>?
+ private var onProgress: (@Sendable (Double) -> Void)?
+
+ func download(_ url: URL, onProgress: @escaping @Sendable (Double) -> Void) async throws -> URL {
+ self.onProgress = onProgress
+ let session = URLSession(configuration: .ephemeral, delegate: self, delegateQueue: nil)
+ defer { session.finishTasksAndInvalidate() }
+ return try await withCheckedThrowingContinuation { continuation in
+ self.continuation = continuation
+ session.downloadTask(with: url).resume()
+ }
+ }
+
+ func urlSession(
+ _: URLSession, downloadTask _: URLSessionDownloadTask, didWriteData _: Int64,
+ totalBytesWritten written: Int64, totalBytesExpectedToWrite expected: Int64
+ ) {
+ if expected > 0 { onProgress?(Double(written) / Double(expected)) }
+ }
+
+ func urlSession(_: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
+ let status = (downloadTask.response as? HTTPURLResponse)?.statusCode ?? 200
+ guard (200..<300).contains(status) else {
+ continuation?.resume(throwing: URLError(.badServerResponse))
+ continuation = nil
+ return
+ }
+ let kept = FileManager.default.temporaryDirectory.appendingPathComponent("browsentic-node-\(UUID().uuidString).tar.gz")
+ do {
+ try FileManager.default.moveItem(at: location, to: kept)
+ continuation?.resume(returning: kept)
+ } catch {
+ continuation?.resume(throwing: error)
+ }
+ continuation = nil
+ }
+
+ func urlSession(_: URLSession, task _: URLSessionTask, didCompleteWithError error: Error?) {
+ guard let error else { return }
+ continuation?.resume(throwing: error)
+ continuation = nil
+ }
+}
diff --git a/src/mac/Sources/Browsentic/Core/Paths.swift b/src/mac/Sources/Browsentic/Core/Paths.swift
new file mode 100644
index 0000000..72e2aca
--- /dev/null
+++ b/src/mac/Sources/Browsentic/Core/Paths.swift
@@ -0,0 +1,40 @@
+import Foundation
+
+enum Paths {
+ static let home = FileManager.default.homeDirectoryForCurrentUser
+
+ static let state = home.appendingPathComponent(".browsentic", isDirectory: true)
+ static let cli = state.appendingPathComponent("cli", isDirectory: true)
+ static let cliEntry = cli.appendingPathComponent("dist/cli.js")
+ static let cliManifest = cli.appendingPathComponent("package.json")
+ static let appMarker = cli.appendingPathComponent(".browsentic-app.json")
+ static let bin = state.appendingPathComponent("bin", isDirectory: true)
+ static let shim = bin.appendingPathComponent("browsentic")
+ static let mcpShim = bin.appendingPathComponent("browsentic-mcp")
+ static let runtime = state.appendingPathComponent("runtime", isDirectory: true)
+ static let privateNode = runtime.appendingPathComponent("node/bin/node")
+ static let lockfile = state.appendingPathComponent("daemon.json")
+ static let log = state.appendingPathComponent("daemon.log")
+ static let config = state.appendingPathComponent("config.json")
+
+ static let user = home.appendingPathComponent("browsentic", isDirectory: true)
+ static let defaultExtension = user.appendingPathComponent("extension/chrome-mv3", isDirectory: true)
+
+ static var payload: URL? {
+ Bundle.main.resourceURL?.appendingPathComponent("payload", isDirectory: true)
+ }
+
+ static func extensionDir() -> URL {
+ guard
+ let data = try? Data(contentsOf: config),
+ let stored = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let chosen = stored["extensionDir"] as? String, !chosen.isEmpty
+ else { return defaultExtension }
+ return URL(fileURLWithPath: (chosen as NSString).expandingTildeInPath, isDirectory: true)
+ }
+
+ static func tilde(_ url: URL) -> String {
+ let path = url.path
+ return path.hasPrefix(home.path) ? "~" + path.dropFirst(home.path.count) : path
+ }
+}
diff --git a/src/mac/Sources/Browsentic/Core/Payload.swift b/src/mac/Sources/Browsentic/Core/Payload.swift
new file mode 100644
index 0000000..45def53
--- /dev/null
+++ b/src/mac/Sources/Browsentic/Core/Payload.swift
@@ -0,0 +1,129 @@
+import Foundation
+
+enum PayloadError: LocalizedError {
+ case missing
+
+ var errorDescription: String? {
+ "This copy of Browsentic.app carries no CLI payload — download a fresh one from browsentic.com."
+ }
+}
+
+/// The CLI, the bundled skills and the extension build, shipped inside the app bundle in the same
+/// layout as the npm package and laid down in ~/.browsentic/cli.
+enum Payload {
+ static func version(at manifest: URL) -> String? {
+ guard
+ let data = try? Data(contentsOf: manifest),
+ let parsed = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
+ else { return nil }
+ return parsed["version"] as? String
+ }
+
+ static var bundledVersion: String? {
+ Paths.payload.flatMap { version(at: $0.appendingPathComponent("package.json")) }
+ }
+
+ static var installedVersion: String? {
+ FileManager.default.fileExists(atPath: Paths.cliEntry.path) ? version(at: Paths.cliManifest) : nil
+ }
+
+ static var isCurrent: Bool {
+ guard let bundled = bundledVersion, let installed = installedVersion else { return false }
+ return installed == bundled && FileManager.default.fileExists(atPath: Paths.appMarker.path)
+ }
+
+ /// A directory swap, which is safe here and not for the extension: Node has already read the
+ /// one bundled file a running daemon needs, and nothing derives an identity from this path.
+ static func install(node: NodeInstall) throws {
+ guard let source = Paths.payload, let version = bundledVersion else { throw PayloadError.missing }
+ let files = FileManager.default
+ try files.createDirectory(at: Paths.state, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
+
+ let staging = Paths.state.appendingPathComponent("cli.tmp-\(ProcessInfo.processInfo.processIdentifier)")
+ try? files.removeItem(at: staging)
+ try files.copyItem(at: source, to: staging)
+
+ let marker: [String: Any] = [
+ "version": version,
+ "app": Bundle.main.bundlePath,
+ "installedAt": ISO8601DateFormatter().string(from: Date()),
+ ]
+ try JSONSerialization.data(withJSONObject: marker, options: [.prettyPrinted, .sortedKeys])
+ .write(to: staging.appendingPathComponent(Paths.appMarker.lastPathComponent))
+
+ let retired = Paths.state.appendingPathComponent("cli.old-\(ProcessInfo.processInfo.processIdentifier)")
+ if files.fileExists(atPath: Paths.cli.path) { try files.moveItem(at: Paths.cli, to: retired) }
+ try files.moveItem(at: staging, to: Paths.cli)
+ try? files.removeItem(at: retired)
+
+ try writeShims(node: node)
+ }
+
+ static func writeShims(node: NodeInstall) throws {
+ let files = FileManager.default
+ try files.createDirectory(at: Paths.bin, withIntermediateDirectories: true)
+ let resolve = """
+ NODE="\(node.path)"
+ [ -x "$NODE" ] || NODE="$HOME/.browsentic/runtime/node/bin/node"
+ [ -x "$NODE" ] || NODE="$(command -v node)"
+ if [ -z "$NODE" ]; then
+ echo "browsentic: Node.js \(NodeRuntime.minimumMajor) or newer is missing — open Browsentic.app and it will install it." >&2
+ exit 127
+ fi
+ """
+ let shims: [(URL, String)] = [
+ (Paths.shim, ""),
+ (Paths.mcpShim, "[ $# -eq 0 ] && set -- mcp\n"),
+ ]
+ for (url, prelude) in shims {
+ let script = "#!/bin/sh\n# Written by Browsentic.app — edits are replaced on the next update.\n\(resolve)\n\(prelude)exec \"$NODE\" \"$HOME/.browsentic/cli/dist/cli.js\" \"$@\"\n"
+ try script.write(to: url, atomically: true, encoding: .utf8)
+ try files.setAttributes([.posixPermissions: 0o755], ofItemAtPath: url.path)
+ }
+ }
+}
+
+/// Puts `browsentic` on the terminal's PATH by symlinking the shim into a directory that is
+/// already there and already writable, so no shell profile is edited and no password is asked for.
+enum CommandLink {
+ static let names = ["browsentic", "browsentic-mcp"]
+
+ static var candidates: [String] {
+ Shell.loginPath.filter { dir in
+ dir.hasPrefix(NSHomeDirectory()) || dir == "/usr/local/bin" || dir == "/opt/homebrew/bin"
+ }.filter { !$0.hasPrefix(Paths.state.path) && FileManager.default.isWritableFile(atPath: $0) }
+ }
+
+ static var linkedIn: String? {
+ Shell.loginPath.first { dir in
+ (try? FileManager.default.destinationOfSymbolicLink(atPath: "\(dir)/browsentic")) == Paths.shim.path
+ }
+ }
+
+ /// A `browsentic` that is on the PATH but is not ours — an npm global, or a source checkout link.
+ static var foreign: String? {
+ guard linkedIn == nil, let found = Shell.which("browsentic") else { return nil }
+ return found
+ }
+
+ static func link() throws -> String {
+ guard let dir = candidates.first else {
+ throw CocoaError(.fileWriteNoPermission, userInfo: [
+ NSLocalizedDescriptionKey: "No writable directory on your PATH — add \(Paths.tilde(Paths.bin)) to it in ~/.zprofile instead.",
+ ])
+ }
+ for name in names {
+ let link = "\(dir)/\(name)"
+ if (try? FileManager.default.destinationOfSymbolicLink(atPath: link)) != nil {
+ try FileManager.default.removeItem(atPath: link)
+ }
+ try FileManager.default.createSymbolicLink(atPath: link, withDestinationPath: Paths.bin.appendingPathComponent(name).path)
+ }
+ return dir
+ }
+
+ static func unlink() {
+ guard let dir = linkedIn else { return }
+ for name in names { try? FileManager.default.removeItem(atPath: "\(dir)/\(name)") }
+ }
+}
diff --git a/src/mac/Sources/Browsentic/Core/Preflight.swift b/src/mac/Sources/Browsentic/Core/Preflight.swift
new file mode 100644
index 0000000..8bf3adf
--- /dev/null
+++ b/src/mac/Sources/Browsentic/Core/Preflight.swift
@@ -0,0 +1,101 @@
+import AppKit
+import Foundation
+
+enum CheckID: String, CaseIterable, Identifiable {
+ case system, node, command, extensionFiles, browser, agent
+
+ var id: String { rawValue }
+
+ var title: String {
+ switch self {
+ case .system: "This Mac"
+ case .node: "Node.js runtime"
+ case .command: "Browsentic command"
+ case .extensionFiles: "Browser extension"
+ case .browser: "A Chromium browser"
+ case .agent: "An AI agent"
+ }
+ }
+
+ var icon: String {
+ switch self {
+ case .system: "laptopcomputer"
+ case .node: "hexagon"
+ case .command: "terminal"
+ case .extensionFiles: "puzzlepiece.extension"
+ case .browser: "globe"
+ case .agent: "sparkles"
+ }
+ }
+
+ /// What "Set up everything" installs on its own. A browser and an agent are the user's pick.
+ var installsAutomatically: Bool { self == .node || self == .command || self == .extensionFiles }
+ var blocksEntry: Bool { installsAutomatically }
+}
+
+enum CheckState: Equatable {
+ case waiting
+ case checking
+ case passed(String)
+ case missing(String)
+ case advisory(String)
+ case working(Double?, String)
+ case failed(String)
+
+ var isPassed: Bool { if case .passed = self { true } else { false } }
+ var needsAttention: Bool {
+ switch self {
+ case .missing, .failed: true
+ default: false
+ }
+ }
+}
+
+struct Browser: Identifiable, Equatable {
+ let name: String
+ let bundleId: String
+ let url: URL
+
+ var id: String { bundleId }
+
+ static let known: [(String, String)] = [
+ ("Google Chrome", "com.google.Chrome"),
+ ("Brave", "com.brave.Browser"),
+ ("Microsoft Edge", "com.microsoft.edgemac"),
+ ("Arc", "company.thebrowser.Browser"),
+ ("Vivaldi", "com.vivaldi.Vivaldi"),
+ ("Opera", "com.operasoftware.Opera"),
+ ("Chromium", "org.chromium.Chromium"),
+ ]
+
+ static func installed() -> [Browser] {
+ known.compactMap { name, bundleId in
+ NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleId).map { Browser(name: name, bundleId: bundleId, url: $0) }
+ }
+ }
+
+ /// Chrome refuses chrome:// URLs from the command line, but takes them over Apple Events.
+ @discardableResult
+ func openExtensionsPage() -> Bool {
+ let source = "tell application id \"\(bundleId)\"\nactivate\nopen location \"chrome://extensions\"\nend tell"
+ var error: NSDictionary?
+ NSAppleScript(source: source)?.executeAndReturnError(&error)
+ if error != nil { NSWorkspace.shared.openApplication(at: url, configuration: .init()) }
+ return error == nil
+ }
+}
+
+enum AgentProbe {
+ static let bins = [("Claude Code", "claude"), ("Codex", "codex"), ("Antigravity", "agy")]
+
+ static func installed() -> [String] {
+ bins.filter { Shell.which($0.1) != nil }.map(\.0)
+ }
+}
+
+enum ExtensionFiles {
+ static func stamp() -> InstallStamp? {
+ let url = Paths.extensionDir().appendingPathComponent(".browsentic-install.json")
+ return (try? Data(contentsOf: url)).flatMap { try? JSONDecoder().decode(InstallStamp.self, from: $0) }
+ }
+}
diff --git a/src/mac/Sources/Browsentic/Core/Shell.swift b/src/mac/Sources/Browsentic/Core/Shell.swift
new file mode 100644
index 0000000..9495418
--- /dev/null
+++ b/src/mac/Sources/Browsentic/Core/Shell.swift
@@ -0,0 +1,121 @@
+import Foundation
+
+struct ShellResult {
+ let status: Int32
+ let stdout: String
+ let stderr: String
+
+ var ok: Bool { status == 0 }
+ var failure: String {
+ let text = stderr.trimmingCharacters(in: .whitespacesAndNewlines)
+ return text.isEmpty ? stdout.trimmingCharacters(in: .whitespacesAndNewlines) : text
+ }
+}
+
+enum Shell {
+ static let fallbackPath = [
+ "\(NSHomeDirectory())/.local/bin", "/opt/homebrew/bin", "/usr/local/bin",
+ "/usr/bin", "/bin", "/usr/sbin", "/sbin",
+ ]
+
+ /// A GUI app inherits launchd's PATH, which has neither Homebrew nor ~/.local/bin on it.
+ /// The daemon spawns the agent CLI by name, so it has to be started with the PATH the
+ /// user's own terminal would have given it.
+ static let loginPath: [String] = {
+ let shell = ProcessInfo.processInfo.environment["SHELL"] ?? "/bin/zsh"
+ let marker = "__BROWSENTIC_PATH__"
+ let result = runSync(shell, ["-ilc", "printf '\(marker)%s\(marker)' \"$PATH\""], timeout: 6)
+ let parts = result.stdout.components(separatedBy: marker)
+ let found = parts.count >= 3 ? parts[1].split(separator: ":").map(String.init) : []
+ var seen = Set<String>()
+ return (found + fallbackPath).filter { !$0.isEmpty && seen.insert($0).inserted }
+ }()
+
+ static func environment(extraPath: [String] = []) -> [String: String] {
+ var env = ProcessInfo.processInfo.environment
+ env["PATH"] = (extraPath + loginPath).joined(separator: ":")
+ env.removeValue(forKey: "BROWSENTIC_AGENT_RUN")
+ return env
+ }
+
+ static func which(_ name: String) -> String? {
+ loginPath.map { "\($0)/\(name)" }.first { FileManager.default.isExecutableFile(atPath: $0) }
+ }
+
+ static func run(
+ _ executable: String, _ arguments: [String], extraPath: [String] = [], timeout: TimeInterval = 120,
+ onLine: (@Sendable (String) -> Void)? = nil
+ ) async -> ShellResult {
+ await withCheckedContinuation { continuation in
+ DispatchQueue.global(qos: .userInitiated).async {
+ continuation.resume(returning: runSync(
+ executable, arguments, environment: environment(extraPath: extraPath), timeout: timeout, onLine: onLine
+ ))
+ }
+ }
+ }
+
+ static func runSync(
+ _ executable: String, _ arguments: [String], environment: [String: String]? = nil, timeout: TimeInterval,
+ onLine: (@Sendable (String) -> Void)? = nil
+ ) -> ShellResult {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: executable)
+ process.arguments = arguments
+ if let environment { process.environment = environment }
+ process.standardInput = FileHandle.nullDevice
+
+ let out = Pipe(), err = Pipe()
+ process.standardOutput = out
+ process.standardError = err
+
+ let collected = Collected()
+ out.fileHandleForReading.readabilityHandler = { handle in
+ let data = handle.availableData
+ guard !data.isEmpty else { return }
+ collected.append(data, to: \.out)
+ if let onLine, let text = String(data: data, encoding: .utf8) {
+ text.split(whereSeparator: \.isNewline).forEach { onLine(String($0)) }
+ }
+ }
+ err.fileHandleForReading.readabilityHandler = { handle in
+ let data = handle.availableData
+ guard !data.isEmpty else { return }
+ collected.append(data, to: \.err)
+ if let onLine, let text = String(data: data, encoding: .utf8) {
+ text.split(whereSeparator: \.isNewline).forEach { onLine(String($0)) }
+ }
+ }
+
+ do { try process.run() } catch {
+ return ShellResult(status: 127, stdout: "", stderr: error.localizedDescription)
+ }
+
+ let killer = DispatchWorkItem { if process.isRunning { process.terminate() } }
+ DispatchQueue.global().asyncAfter(deadline: .now() + timeout, execute: killer)
+ process.waitUntilExit()
+ killer.cancel()
+
+ out.fileHandleForReading.readabilityHandler = nil
+ err.fileHandleForReading.readabilityHandler = nil
+ collected.append(out.fileHandleForReading.readDataToEndOfFile(), to: \.out)
+ collected.append(err.fileHandleForReading.readDataToEndOfFile(), to: \.err)
+
+ return ShellResult(status: process.terminationStatus, stdout: collected.text(\.out), stderr: collected.text(\.err))
+ }
+
+ private final class Collected: @unchecked Sendable {
+ var out = Data(), err = Data()
+ private let lock = NSLock()
+
+ func append(_ data: Data, to key: ReferenceWritableKeyPath<Collected, Data>) {
+ lock.lock(); defer { lock.unlock() }
+ self[keyPath: key].append(data)
+ }
+
+ func text(_ key: KeyPath<Collected, Data>) -> String {
+ lock.lock(); defer { lock.unlock() }
+ return String(data: self[keyPath: key], encoding: .utf8) ?? ""
+ }
+ }
+}
diff --git a/src/mac/Tests/BrowsenticTests/ModelTests.swift b/src/mac/Tests/BrowsenticTests/ModelTests.swift
new file mode 100644
index 0000000..5a3afe9
--- /dev/null
+++ b/src/mac/Tests/BrowsenticTests/ModelTests.swift
@@ -0,0 +1,59 @@
+import Foundation
+import Testing
+@testable import Browsentic
+
+@Suite struct VersionTests {
+ @Test func comparesReleases() {
+ #expect(Version.isNewer("0.5.1", than: "0.5.0"))
+ #expect(Version.isNewer("0.10.0", than: "0.9.9"))
+ #expect(!Version.isNewer("0.5.0", than: "0.5.0"))
+ #expect(!Version.isNewer("0.4.15", than: "0.5.0"))
+ }
+
+ @Test func readsNodeMajor() {
+ #expect(Version.major("v22.11.0\n") == 22)
+ #expect(Version.major("18.2.0") == 18)
+ #expect(Version.major("") == 0)
+ }
+}
+
+@Suite struct PairingCodeTests {
+ @Test func groupsForReadingAloud() {
+ let pairing = PairingCode(code: "ABCD2345", expiresAt: 1_790_000_000_000)
+ #expect(pairing.grouped == "ABCD-2345")
+ #expect(pairing.expiry == Date(timeIntervalSince1970: 1_790_000_000))
+ }
+}
+
+@Suite struct DecodingTests {
+ @Test func statusFrameWithoutAnExtension() throws {
+ let frame = #"{"connected":false,"daemonVersion":"0.5.0","protocolVersion":16,"port":8765,"manifestInSync":true,"pairedBrowsers":0,"pairingPending":false}"#
+ let status = try JSONDecoder().decode(BridgeStatus.self, from: Data(frame.utf8))
+ #expect(status.extensionVersion == nil)
+ #expect(status.port == 8765)
+ }
+
+ @Test func agentListingCarriesTheCatalog() throws {
+ let listing = """
+ {"active":"claude","runners":[{"kind":"codex","bin":"codex","ready":false,
+ "problem":{"code":"AGENT_MISSING","message":"Codex is not installed","fix":"npm i -g @openai/codex"}}],
+ "catalog":[{"kind":"codex","label":"Codex","vendor":"OpenAI","bin":"codex","install":"npm i -g @openai/codex","docs":"https://x","models":["a"]},
+ {"kind":"antigravity","label":"Antigravity","vendor":"Google","bin":"agy","install":"https://antigravity.google/docs/cli/install","docs":"https://y","models":[]}]}
+ """
+ let state = try JSONDecoder().decode(AgentState.self, from: Data(listing.utf8))
+ #expect(state.runners[0].problem?.grantable == nil)
+ #expect(state.catalog?[0].installsWithNpm == true)
+ #expect(state.catalog?[1].installsWithNpm == false)
+ }
+
+ @Test func sessionShowsTheExtensionIdAlone() throws {
+ let row = #"{"origin":"chrome-extension://abcdef","extensionVersion":"0.5.0","pairedAt":"2026-09-01T10:00:00.000Z","lastSeenAt":"2026-09-01T10:00:00.000Z","connected":true}"#
+ let session = try JSONDecoder().decode(BrowserSession.self, from: Data(row.utf8))
+ #expect(session.extensionId == "abcdef")
+ }
+
+ @Test func timestampsReadTheDaemonsIsoStrings() {
+ #expect(Timestamp.date("2026-09-17T14:21:45.381Z") != nil)
+ #expect(Timestamp.ago("not a date") == "not a date")
+ }
+}