~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
372 lines · 13.9 KB Raw History
#if DEBUG
import HUDKit
import OSLog
import SwiftUI

/// The gallery, for design review, in debug builds only: every drawing HUD
/// makes as a workspace tile with its real header, side by side on a strip
/// as the workspace lays its columns (a screen's width each on a phone, a
/// tile's third on an iPad), from the sample answers `just gallery-data`
/// writes to target/gallery/gallery.json, bundled in Debug: the same ones
/// the web's `just gallery` draws, to compare the two tile for tile. Each
/// tile's body is its result's `_meta.ui` drawn by HUDKit; what it opens or
/// writes does nothing but log. Over each tile, outside its chrome, its
/// entry's id and note, for the reviewer. Reached from Settings, or launched
/// with `-gallery [<entry id>]`.
struct GalleryScreen: View {
	/// The server its tiles' icons, HUD's /icon/<domain>, are read from.
	let server: URL
	/// The entry shown first.
	var start: String?
	/// Closes it, where it is presented.
	var done: (() -> Void)?
	@State private var loaded: Gallery.Loaded?
	@State private var visible: String?
	@Environment(\.horizontalSizeClass) private var size

	var body: some View {
		Group {
			switch loaded {
			case nil:
				ProgressView()
			case .missing:
				ContentUnavailableView {
					Label("No gallery", systemImage: "rectangle.split.3x1")
				} description: {
					Text("Run `just gallery-data`, then build the app again.")
				}
			case .failed(let why):
				ContentUnavailableView {
					Label("Couldn't read the gallery", systemImage: "exclamationmark.triangle")
				} description: {
					Text(why)
				}
			case .ready(let gallery):
				strip(gallery)
			}
		}
		.frame(maxWidth: .infinity, maxHeight: .infinity)
		.hudText()
		.background(.canvas)
		.navigationTitle("Gallery")
		.navigationBarTitleDisplayMode(.inline)
		.toolbar {
			if case .ready(let gallery) = loaded {
				ToolbarItem(placement: .topBarLeading) { jump(gallery) }
			}
			if let done {
				ToolbarItem(placement: .confirmationAction) { Button("Done", action: done) }
			}
		}
		.task {
			guard loaded == nil else { return }
			loaded = Gallery.load(server: server)
			if case .ready(let gallery) = loaded {
				visible = start.flatMap { gallery.heading[$0] != nil ? $0 : nil } ?? gallery.entries.first?.id
			}
		}
	}

	private func strip(_ gallery: Gallery) -> some View {
		let compact = size != .regular
		let count = gallery.entries.count
		return ScrollView(.horizontal) {
			LazyHStack(spacing: Space.s2) {
				ForEach(gallery.entries) { entry in
					VStack(alignment: .leading, spacing: Space.s1) {
						VStack(alignment: .leading, spacing: 0) {
							Text("\(entry.index + 1)/\(count)  \(entry.id)")
								.font(.caption.monospaced())
							Text(entry.note)
								.font(.caption2)
								.lineLimit(2, reservesSpace: true)
						}
						.foregroundStyle(.secondary)
						.padding(.horizontal, Space.s1)
						GalleryTile(entry: entry, from: entry.from.flatMap { gallery.heading[$0] }) {
							withAnimation { visible = entry.from }
						}
					}
					.containerRelativeFrame(.horizontal, count: compact ? 1 : 6, span: compact ? 1 : TileWidth.third.sixths, spacing: Space.s2)
				}
			}
			.scrollTargetLayout()
		}
		.scrollIndicators(.hidden)
		.scrollTargetBehavior(.viewAligned)
		.scrollPosition(id: $visible)
		.contentMargins(.horizontal, Space.s3, for: .scrollContent)
		.contentMargins(.vertical, Space.s2, for: .scrollContent)
	}

	/// The entries by group, one chosen goes to its tile.
	private func jump(_ gallery: Gallery) -> some View {
		Menu {
			ForEach(gallery.groups) { group in
				Section(group.name) {
					ForEach(group.entries) { entry in
						Button(entry.id) { visible = entry.id }
					}
				}
			}
		} label: {
			Label("Entries", systemImage: "list.bullet")
		}
	}
}

/// One entry as a workspace tile: the workspace's header, its result
/// drawn under it as a tile's body draws it.
private struct GalleryTile: View {
	let entry: GalleryEntry
	/// The heading of the tile it was opened from.
	let from: String?
	let goFrom: () -> Void

	var body: some View {
		let id = entry.id
		VStack(spacing: 0) {
			TileHeader(
				title: entry.tile.heading,
				icon: entry.tile.icon,
				symbol: entry.tile.symbol,
				handle: entry.handle,
				mine: entry.mine,
				from: from,
				goFrom: goFrom,
				byAgent: entry.tile.byAgent,
				app: entry.app,
				openApp: { Gallery.log.info("\(id, privacy: .public): open its app") },
				added: entry.tile.byAgent ? "Added by an agent for you" : "Added by you"
			) {
				Button("Remove from canvas", systemImage: "xmark", role: .destructive) {
					Gallery.log.info("\(id, privacy: .public): remove")
				}
			}
			Divider()
			Group {
				if entry.drawn.pagesItself {
					ResultView(drawn: entry.drawn, context: entry.context)
				} else {
					ScrollView {
						VStack(alignment: .leading, spacing: Space.s3) {
							ResultView(drawn: entry.drawn, context: entry.context)
						}
						.frame(maxWidth: .infinity, alignment: .leading)
						.padding(.horizontal, Space.s3)
						.environment(\.listBleed, Space.s3)
						// A bleeding picture, map or tiles first meets the header: no padding over it.
						.padding(.top, entry.drawn.leadsTileWithBleed ? 0 : Space.s2)
						.padding(.bottom, Space.s2)
					}
				}
			}
			.environment(\.shown, Shown(title: entry.tile.heading, handle: entry.handle))
			.background(.tileSurface)
		}
		.tileChrome()
	}
}

/// One entry of gallery.json, read for drawing: its tile (its title,
/// symbol, domain and icon as the workspace's tile has them), the account
/// it shows by handle, its result as drawn, and the inert context it is
/// drawn with.
struct GalleryEntry: Identifiable {
	let id: String
	let index: Int
	let group: String
	let note: String
	let tile: Tile
	/// The entry it was opened from.
	let from: String?
	let handle: String?
	/// Whether the account it shows is the gallery's own.
	let mine: Bool
	/// Its app's name, where its icon opens its app's page.
	let app: String?
	let drawn: Drawn
	let context: ViewContext
}

/// gallery.json (`v` 1), as the contract in `just gallery-data` writes it.
struct Gallery {
	let entries: [GalleryEntry]
	/// Each entry's title, by its id.
	let heading: [String: String]
	let groups: [Group]

	static let log = Logger(subsystem: "place.hud.app", category: "gallery")

	enum Loaded {
		case missing
		case failed(String)
		case ready(Gallery)
	}

	/// The bundled gallery.json, its icons' paths read from `server`.
	static func load(server: URL) -> Loaded {
		guard let url = Bundle.main.url(forResource: "gallery", withExtension: "json") else { return .missing }
		do {
			let json = try JSONDecoder().decode(JSON.self, from: Data(contentsOf: url))
			guard json["v"] == .number(1) else { return .failed("gallery.json is not version 1.") }
			return .ready(Gallery(json, server: server))
		} catch {
			return .failed(error.localizedDescription)
		}
	}

	init(_ json: JSON, server: URL) {
		let me = json["me"]
		let origin = Self.origin(server)
		let tiles = json["tiles"]?.array ?? []
		// What a form asks of a tool (`query`, `link_card`, …): the answer
		// of a tile of that call, as the web's gallery answers it.
		let answers: [Call: JSON] = Dictionary(
			tiles.compactMap { tile in
				guard let name = tile["call"]?.str("name"), let found = tile["result"]?["structuredContent"] else { return nil }
				return (Call(name, tile["call"]?["args"]?.object ?? [:]), Self.moved(found, to: origin))
			}
		) { first, _ in first }
		let made = tiles.enumerated().compactMap { Self.entry($1, at: $0, me: me, server: server, origin: origin, answers: answers) }
		entries = made
		heading = Dictionary(made.map { ($0.id, $0.tile.heading) }) { first, _ in first }
		var groups: [Group] = []
		for entry in made {
			if groups.last?.name == entry.group {
				groups[groups.count - 1].entries.append(entry)
			} else {
				groups.append(Group(name: entry.group, entries: [entry]))
			}
		}
		self.groups = groups
	}

	/// Entries of one app, in order.
	struct Group: Identifiable {
		let name: String
		var entries: [GalleryEntry]
		var id: String { name }
	}

	/// Where the recorded answers' server-proxied URLs (blobs, icons) point:
	/// the server they were recorded from.
	private static let recorded = "http://localhost:8787/"

	/// The app's server's origin, with its slash: `https://host[:port]/`.
	private static func origin(_ server: URL) -> String {
		guard var parts = URLComponents(url: server, resolvingAgainstBaseURL: false) else { return recorded }
		parts.path = ""
		parts.query = nil
		parts.fragment = nil
		return (parts.string ?? "") + "/"
	}

	/// An answer with every URL of the recording server moved to `origin`,
	/// so its blobs and icons load from the app's server, on a device too.
	private static func moved(_ json: JSON, to origin: String) -> JSON {
		switch json {
		case .string(let s) where s.hasPrefix(recorded): .string(origin + s.dropFirst(recorded.count))
		case .array(let a): .array(a.map { moved($0, to: origin) })
		case .object(let o): .object(o.mapValues { moved($0, to: origin) })
		default: json
		}
	}

	private static func entry(_ json: JSON, at index: Int, me: JSON?, server: URL, origin: String, answers: [Call: JSON]) -> GalleryEntry? {
		guard let id = json.str("id"), let header = json["header"], let name = json["call"]?.str("name") else { return nil }
		let arguments = json["call"]?["args"]?.object ?? [:]
		// A tile record as the workspace reads it, so the title, symbol and
		// domain come out of the same code.
		var record: [String: JSON] = ["tool": .string(name), "arguments": .object(arguments), "by": header["agent"] == .bool(true) ? "agent" : "person"]
		if let title = header.str("title") { record["title"] = .string(title) }
		if let from = header.str("from") { record["from"] = .string(from) }
		var view: [String: JSON] = ["key": .string(id), "record": .object(record)]
		if let did = me?.str("did") { view["author"] = .string(did) }
		if let icon = header.str("icon").flatMap({ URL(string: $0, relativeTo: server) }) { view["icon"] = .string(icon.absoluteString) }
		guard let tile = Tile(.object(view)) else { return nil }
		let result = ToolResult(moved(json["result"] ?? [:], to: origin))
		let drawn = Drawn(result)
		let domain = tile.tool == "describe_app" ? nil : header.str("domain") ?? tile.domain
		return GalleryEntry(
			id: id,
			index: index,
			group: json.str("group") ?? "",
			note: json.str("note") ?? "",
			tile: tile,
			from: tile.from,
			handle: handle(header.str("account"), me: me),
			mine: header.str("account").map { $0 == "me" || $0 == me?.str("did") || $0 == me?.str("handle") } ?? false,
			// Its app by name, as a signed-in person's apps name it: the gallery's group, which is the app.
			app: domain.map { domain in json.str("group").flatMap { $0 == "Generic" ? nil : $0 } ?? domain },
			drawn: drawn,
			context: context(id, result: result, drawn: drawn, answers: answers)
		)
	}

	/// The account it shows by handle: as the header names it, `me` as the
	/// gallery's own; a DID it has no handle for, none, as a tile's.
	private static func handle(_ account: String?, me: JSON?) -> String? {
		guard let account else { return nil }
		if account == "me" || account == me?.str("did") { return me?.str("handle") }
		return account.hasPrefix("did:") ? nil : account
	}

	/// The context a tile's result draws with, as a workspace tile's
	/// (`StepView.configure`): its handlers there, so it draws what it
	/// would, but each only logs; a tool a form calls answers as the
	/// gallery's tile of that call does (a write, with nothing written), an
	/// upload with a made-up blob.
	private static func context(_ id: String, result: ToolResult, drawn: Drawn, answers: [Call: JSON]) -> ViewContext {
		let ui: JSON? = if case .tree(let ui) = drawn { ui } else { nil }
		let context = ViewContext()
		context.trusted = ui?["trusted"] == .bool(true)
		context.onOpenActor = { actor in log.info("\(id, privacy: .public): open actor \(actor, privacy: .public)") }
		context.onOpenLink = { url in log.info("\(id, privacy: .public): open link \(url.absoluteString, privacy: .public)") }
		context.onReplace = { call in log.info("\(id, privacy: .public): tab \(call.name, privacy: .public)") }
		context.onCall = { call, _ in log.info("\(id, privacy: .public): open \(call.name, privacy: .public)") }
		if result.viewer != nil {
			context.onAction = { action in
				log.info("\(id, privacy: .public): action \(action.tool.name, privacy: .public)")
				return nil
			}
			context.onTool = { call in
				log.info("\(id, privacy: .public): tool \(call.name, privacy: .public)")
				if let found = answers[call] { return found }
				if call.name == "apply_writes" { return ["results": []] }
				throw HUDError.tool("The gallery has no answer for \(call.name).")
			}
			context.onUpload = { bytes, progress in
				log.info("\(id, privacy: .public): upload \(bytes.count) bytes")
				progress(1)
				return ["$type": "blob", "ref": ["$link": "bafkreigallerygallerygallerygallerygallerygallerygallerygall"], "mimeType": "image/jpeg", "size": .number(Double(bytes.count))]
			}
		}
		context.onMore = { log.info("\(id, privacy: .public): page more") }
		context.onListMore = { call in
			log.info("\(id, privacy: .public): list more \(call.name, privacy: .public)")
			throw HUDError.tool("The gallery has no next page.")
		}
		context.onReload = { log.info("\(id, privacy: .public): reload") }
		if let report = ui?["report"], report["feed"]?.string != nil, report["seen"] == .bool(true) {
			context.onInteraction = { event, _ in log.info("\(id, privacy: .public): interaction \(event, privacy: .public)") }
		}
		return context
	}
}

extension GalleryScreen {
	/// Launched with `-gallery`: the gallery as the app's root, at the entry
	/// whose id follows it, if one does.
	static let launched: Launch? = {
		let arguments = ProcessInfo.processInfo.arguments
		guard let at = arguments.firstIndex(of: "-gallery") else { return nil }
		let next = arguments.indices.contains(at + 1) ? arguments[at + 1] : nil
		return Launch(start: next.flatMap { $0.hasPrefix("-") ? nil : $0 })
	}()

	struct Launch: Sendable {
		let start: String?
	}
}
#endif