chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.3.1 Latest 5 packages
0
0
import AuthenticationServices
import HUDKit
import SafariServices
import SwiftUI
/// The app's state: the server it calls, the accounts signed in to it and
/// the one in use with its workspace, the screens on the stack (each a tool
/// call and what it answered), the page open in Safari, and what it tells
/// feeds of their posts.
@MainActor @Observable
final class Browser {
var path: [Step] = []
var page: Page?
/// The server HUD's tools are called on: hud.place; in a Debug build,
/// the one `-server <url>` named at launch (kept for the launches after,
/// as harness/local.mjs relaunches it), else `just serve` on this Mac.
let serverURL = Browser.chosenServer()
/// What plays the screens' players' tracks: one for the app, so music
/// goes on as one moves about the stack.
let player = AudioPlayer()
/// The account calls are made as, the one in use of those signed in to
/// this server (their tokens in the Keychain); nil for no one, and the
/// app's root is then signing in.
private(set) var session: AccountSession?
/// The accounts signed in to this server, the one in use first, then
/// the one used last.
private(set) var accounts: [KeptAccount] = []
/// Who that is, once a result has said (`_meta.viewer`).
private(set) var viewer: Viewer?
/// The apps it uses, as `describe_repo` of `me` lists them, most
/// collections first; nil until read.
private(set) var apps: [AppLink]?
/// Why they could not be read, until they are.
private(set) var appsError: String?
private(set) var signingIn = false
/// Why the last sign-in did not happen.
var signInError: String?
@ObservationIgnored private(set) var feedback: Interactions!
/// The signed-in account's workspace, which is then the app's root.
private(set) var workspace: Workspace?
/// Whether Home shows over the workspace.
var showingHome = false
/// Whether Settings shows over the workspace.
var showingSettings = false
/// The canvas whose share sheet shows.
var sharing: Shared?
/// Each tile's call and what it answered, by the tile's id, kept while
/// its column is off screen.
@ObservationIgnored private var tileSteps: [String: Step] = [:]
init() {
feedback = Interactions { [weak self] feed, interactions in
guard let self else { return (0, nil) }
let result = try await self.client.call(Call("send_interactions", ["feed": .string(feed), "interactions": .array(interactions)]))
if result.isError { throw HUDError.tool(result.text.isEmpty ? "send_interactions failed." : result.text) }
return (Int(result.structuredContent?["sent"]?.number ?? 0), result.structuredContent?["reason"]?.string)
}
player.publishToSystem()
adopt(AccountSession.restore(serverURL, ended: ended))
// `-call '{"name": …, "args": {…}}'` at launch opens that call, for
// development and screenshots (`xcrun simctl launch … -call …`).
let arguments = ProcessInfo.processInfo.arguments
if let at = arguments.firstIndex(of: "-call"), at + 1 < arguments.count,
let found = try? JSONDecoder().decode(JSON.self, from: Data(arguments[at + 1].utf8)),
let name = found["name"]?.string
{
path = [Step(call: Call(name, found["args"]?.object ?? [:]))]
}
}
private static func chosenServer() -> URL {
#if DEBUG
let defaults = UserDefaults.standard
if let given = defaults.volatileDomain(forName: UserDefaults.argumentDomain)["server"] as? String, let id = Bundle.main.bundleIdentifier {
defaults.setPersistentDomain((defaults.persistentDomain(forName: id) ?? [:]).merging(["server": given]) { _, new in new }, forName: id)
}
return defaults.string(forKey: "server").flatMap(URL.init(string:)) ?? URL(string: "http://localhost:8787")!
#else
return URL(string: "https://hud.place")!
#endif
}
var client: HUDClient {
HUDClient(base: serverURL, session: session)
}
/// Calls made as `session` from now on, with its workspace; what was
/// open as the account before (tiles, screens, sheets) let go.
private func adopt(_ session: AccountSession?) {
self.session = session
accounts = AccountSession.kept(serverURL)
viewer = nil
apps = nil
appsError = nil
workspace = session.map { Workspace(client: WorkspaceClient(base: serverURL, session: $0)) }
tileSteps = [:]
path = []
showingHome = false
showingSettings = false
sharing = nil
}
/// What a session tells when it ends, by a refused renewal, signing out
/// or deleting its data: the app goes on as the account used before it,
/// else signed out.
private var ended: AccountSession.Ended {
{ [weak self] gone in
guard let self else { return }
guard self.session === gone else {
self.accounts = AccountSession.kept(self.serverURL)
return
}
self.adopt(AccountSession.restore(self.serverURL, ended: self.ended))
}
}
/// Sign in to the server as `handle` (or a DID), in the system's browser
/// sheet, which shares Safari's cookies so the account's own server may
/// know the person already: the handle goes as the request's
/// `login_hint`, so HUD sends it straight on to that server. Signed in
/// as another account already, that one is kept, and this one is in
/// use from now on. Whether it did; why not in `signInError`.
@discardableResult
func signIn(_ handle: String, using web: WebAuthenticationSession) async -> Bool {
guard !signingIn else { return false }
signingIn = true
signInError = nil
defer { signingIn = false }
var hint = Substring(handle.trimmingCharacters(in: .whitespaces))
if hint.hasPrefix("@") { hint = hint.dropFirst() }
do {
let auth = try await AuthServer.discover(serverURL)
let request = SignInRequest(server: auth, hint: String(hint))
let callback = try await web.authenticate(using: request.url, callbackURLScheme: AuthServer.callbackScheme, preferredBrowserSession: .shared)
let tokens = try await auth.exchange(request.code(from: callback), for: request)
// What feeds were told goes as the account it was told as.
if session != nil { await feedback.flush() }
let named = hint.isEmpty || hint.hasPrefix("did:") ? nil : hint.lowercased()
adopt(try AccountSession.start(server: auth, tokens: tokens, handle: named, ended: ended))
await identify()
return true
} catch let error as ASWebAuthenticationSessionError where error.code == .canceledLogin {
return false
} catch {
signInError = error.localizedDescription
return false
}
}
/// Go on as another account kept for this server, `did`: what feeds were
/// told goes first, as the account in use.
func use(_ did: String) async {
guard did != session?.did else { return }
await feedback.flush()
guard let found = AccountSession.restore(serverURL, did: did, ended: ended) else {
accounts = AccountSession.kept(serverURL)
return
}
adopt(found)
}
/// Who the session is and the apps it uses: `describe_repo` of `me`,
/// its `_meta.viewer` and `structuredContent.apps`; read once, or
/// `again`. Its handle is kept for the accounts' list.
func identify(again: Bool = false) async {
guard let session, again || viewer == nil || apps == nil else { return }
do {
let result = try await client.call(Call("describe_repo", ["actor": "me"]))
guard self.session === session else { return }
if result.isError { throw HUDError.tool(result.text.isEmpty ? "Couldn't read your repository." : result.text) }
if let found = result.viewer {
viewer = found
if let handle = found.handle, found.did == session.did, accounts.first(where: { $0.did == found.did })?.handle != handle {
session.name(handle)
accounts = AccountSession.kept(serverURL)
}
}
apps = (result.structuredContent?["apps"]?.array ?? []).compactMap(AppLink.init)
appsError = nil
} catch {
guard self.session === session, (error as? HUDError) != .signIn, !(error is CancellationError) else { return }
appsError = error.localizedDescription
}
}
/// Sign out of the account in use: what feeds were told goes first, as
/// the account; then the session is revoked at the server and dropped
/// from the Keychain, and the app goes on as the account used before
/// it, else signed out (`ended`).
func signOut() async {
guard let session else { return }
await feedback.flush()
await session.signOut()
}
/// Delete everything HUD keeps for the account in use, for good
/// (`deleteAccountData`): what feeds were told goes first, as the
/// account. The server ends every session of the account, so this one is
/// dropped from the Keychain without revoking it, and the app goes on as
/// the account used before it, else signed out (`ended`).
func deleteData() async throws {
guard let session, let workspace else { return }
await feedback.flush()
_ = try await workspace.client.deleteAccountData(did: session.did)
await session.forget()
}
/// Call a tool on a screen of its own, pushed on the stack. What the
/// screen on top told its feed goes first.
func go(_ call: Call) {
Task { await feedback.flush() }
path.append(Step(call: call))
}
/// A tab chosen on a screen: its call on a screen in that one's place,
/// never pushed over it, with no animation, as a segmented control
/// switches what it shows.
func replace(_ step: Step, with call: Call) {
guard let at = path.lastIndex(of: step) else { return go(call) }
Task { await feedback.flush() }
var still = Transaction()
still.disablesAnimations = true
withTransaction(still) { path[at] = Step(call: call) }
}
/// Open a call from Home or Settings: signed in, a tile of the canvas on
/// screen, right of the column on screen; else a screen of its own.
func launch(_ call: Call) {
guard let workspace, let canvas = workspace.current else { return go(call) }
showingHome = false
showingSettings = false
Task { await workspace.add(call, from: nil, on: canvas) }
}
/// A tile's call and what it answered.
func step(for tile: Tile) -> Step {
if let found = tileSteps[tile.id], found.call == tile.call { return found }
let made = Step(call: tile.call)
tileSteps[tile.id] = made
return made
}
/// Forget the tiles no longer on any open canvas.
func keepSteps(_ ids: Set<String>) {
tileSteps = tileSteps.filter { ids.contains($0.key) }
}
/// The tile whose player plays now, and its canvas; none for what plays
/// from a screen of the stack, or nothing.
func playingTile() -> (canvas: String, tile: String)? {
guard let origin = player.origin, let workspace,
let tile = tileSteps.first(where: { AnyHashable($0.value) == origin })?.key,
let canvas = workspace.open.first(where: { workspace.tiles[$0]?.contains { $0.id == tile } == true })
else { return nil }
return (canvas, tile)
}
/// Go to where what plays is: its screen of the stack, or its tile, its
/// canvas shown and its column slid into view, with what covers it closed.
func goToPlaying() {
if let at = path.lastIndex(where: { AnyHashable($0) == player.origin }) {
path = Array(path.prefix(at + 1))
return
}
guard let workspace, let (canvas, tile) = playingTile() else { return }
showingHome = false
showingSettings = false
sharing = nil
path = []
Task {
if workspace.current != canvas { await workspace.activate(canvas) }
workspace.show(canvas, tile)
}
}
func open(_ url: URL) {
page = Page(url: url)
}
}
/// A web page shown in Safari, over the app.
struct Page: Identifiable {
let url: URL
var id: URL { url }
}
/// A canvas whose people show in the share sheet.
struct Shared: Identifiable {
let id: String
}
/// An app the account uses: its domain, its name and its icon (HUD's
/// /icon/<domain>).
struct AppLink: Identifiable, Hashable {
let domain: String
let name: String
let icon: URL?
var id: String { domain }
init?(_ json: JSON) {
guard let domain = json.str("domain") else { return nil }
self.domain = domain
name = json.str("name") ?? domain
icon = json.str("icon").flatMap(URL.init(string:))
}
/// Its app page, for `actor` where given.
func page(for actor: String? = nil) -> Call {
var args: [String: JSON] = ["domain": .string(domain)]
if let actor { args["actor"] = .string(actor) }
return Call("describe_app", args)
}
}
struct SafariView: UIViewControllerRepresentable {
let url: URL
func makeUIViewController(context: Context) -> SFSafariViewController {
SFSafariViewController(url: url)
}
func updateUIViewController(_ controller: SFSafariViewController, context: Context) {}
}
/// One screen: a tool call, what it answered (grown by each page more), and
/// the context its view draws with.
@MainActor @Observable
final class Step: Hashable {
let call: Call
var drawn: Drawn?
var loadingMore = false
var moreError: String?
/// The account the latest result was made for.
var viewer: Viewer?
/// Whether the latest call needed an account it was not made as.
var needsSignIn = false
/// Whether something newer came than the items drawn (`peek`).
var fresh = false
/// The posts this screen has told its feed were seen.
@ObservationIgnored var told: Set<String> = []
/// When it was last read, or asked whether something newer came.
@ObservationIgnored var checked = Date.distantPast
/// How far down it was scrolled, from its top: kept as its tile scrolls
/// off the strip and its view goes, to scroll back to as it comes back.
@ObservationIgnored var offset: CGFloat = 0
@ObservationIgnored private var peeking = false
init(call: Call) {
self.call = call
}
nonisolated static func == (a: Step, b: Step) -> Bool { a === b }
nonisolated func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) }
var title: String {
switch call.name {
case "describe_repo": return call.args["actor"]?.string ?? "Account"
case "describe_app":
if case .tree(let ui) = drawn, let title = ui.str("title") { return title }
return call.args["domain"]?.string ?? "App"
case "list_records", "get_record":
if case .tree(let ui) = drawn, let title = ui.str("title") { return title }
return call.args["collection"]?.string ?? "Record"
case "query":
switch call.args["method"]?.string {
case "app.bsky.feed.getFeed": return "Feed"
case "app.bsky.feed.getTimeline": return "Following"
case "app.bsky.feed.getAuthorFeed": return "Posts"
case "app.bsky.feed.getPostThread": return "Thread"
case "app.bsky.actor.getProfile": return "Profile"
case "app.bsky.feed.getFeedGenerators": return "Feeds"
case let method?: return method
case nil: return "Query"
}
default: return call.name
}
}
/// Call it afresh. A load cancelled (its tile scrolled off the strip, a
/// pull to refresh let go) leaves what was drawn as it was: a tile never
/// drawn loads when it next comes into view, and one drawn keeps its
/// scroll.
func load(_ client: HUDClient) async {
do {
let result = try await client.call(call)
if !result.isError { viewer = result.viewer }
needsSignIn = false
drawn = Drawn(result)
fresh = false
checked = .now
} catch is CancellationError {
} catch let error as URLError where error.code == .cancelled {
} catch {
needsSignIn = (error as? HUDError) == HUDError.signIn
if needsSignIn { viewer = nil }
drawn = .error(error.localizedDescription)
}
}
/// Ask whether something newer came than what it drew: its newest item
/// alone, as its tree's `latest` calls it. A failure says nothing, and
/// the next ask asks again.
func peek(_ client: HUDClient) async {
guard !fresh, !peeking, let latest = drawn?.latest else { return }
peeking = true
checked = .now
defer { peeking = false }
guard let result = try? await client.call(latest.call), !Task.isCancelled else { return }
// What it drew is what was asked of: not read again meanwhile.
if drawn?.latest?.keys == latest.keys, latest.isNewer(Drawn(result)) { fresh = true }
}
/// A page more, its tree's `next`.
func loadMore(_ client: HUDClient) async {
guard !loadingMore, let drawn, let next = drawn.nextPage else { return }
loadingMore = true
moreError = nil
defer { loadingMore = false }
do {
let page = Drawn(try await client.call(next))
if case .error(let message) = page {
moreError = message
} else if let grown = self.drawn?.appending(page) {
self.drawn = grown
} else {
moreError = "The next page is not of this list."
}
} catch {
moreError = error.localizedDescription
}
}
}