chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.4.0 Latest 5 packages
0
0
import Foundation
import SwiftUI
import Testing
@testable import HUDKit
// The rules HUDKit shares with the web renderer, where a port slips most
// easily: reading a tool result into what draws it, paging a resolved
// tree, a conversation's bubbles in order and in runs, and what an action
// or a conversation's box sends, stamped as it is sent; what a form sends,
// its text marked as the server marks it and its photos' EXIF as Grain
// writes it; and what sign-in takes back from the browser.
private func fixture(_ name: String) throws -> ToolResult {
let url = try #require(Bundle.module.url(forResource: name, withExtension: "json", subdirectory: "Fixtures"))
let answer = try JSONDecoder().decode(JSON.self, from: Data(contentsOf: url))
return ToolResult(try #require(answer["result"]))
}
/// The conversation fixture: what it is drawn as, and its `Messages` node.
private func conversation() throws -> (drawn: Drawn, root: JSON) {
let drawn = Drawn(try fixture("ui-messages"))
guard case .tree(let ui) = drawn else { throw HUDError.tool("not a tree: \(drawn)") }
return (drawn, try #require(ui["root"]))
}
@Suite struct Results {
@Test func aResolvedFeedDrawsFromItsTreeAndPagesByItsNext() throws {
let drawn = Drawn(try fixture("ui-feed"))
guard case .tree(let ui) = drawn else {
Issue.record("not a tree: \(drawn)")
return
}
let next = try #require(ui["next"])
let call = try #require(drawn.nextPage)
#expect(call.name == next["name"]?.string)
#expect(JSON.object(call.args) == next["args"])
let count = try #require(ui["root"]?["items"]?.array?.count)
#expect(count > 0)
// A page more: its items after these, and its next taken.
let later = Drawn.tree(ui.merged(with: ["next": ["name": "query", "args": ["cursor": "later"]]]))
let twice = try #require(drawn.appending(later))
guard case .tree(let grown) = twice else { return }
#expect(grown["root"]?["items"]?.array?.count == count * 2)
#expect(twice.nextPage == Call("query", ["cursor": "later"]))
}
@Test func aFailureIsAnError() {
let failed = ToolResult(["isError": true, "content": [["type": "text", "text": "nope"]]])
guard case .error(let message) = Drawn(failed) else {
Issue.record("not an error")
return
}
#expect(message == "nope")
}
/// A tile's header says the title and the handle: the lead at the tree's
/// top does not say them again, and a header with nothing else goes.
@Test func theLeadLeavesOutWhatTheTileShows() {
let shown = Shown(title: "Liked tracks", handle: "dan.test")
let bare: JSON = ["c": "Stack", "k": [
["c": "Header", "p": ["title": "liked tracks", "meta": ["@dan.test"]]],
["c": "Text", "p": ["value": "x"]],
]]
#expect(shown.strip(bare)["k"]?.array?.map { $0["c"] } == ["Text"])
let more: JSON = ["c": "Header", "p": ["title": "Liked tracks", "subtitle": "12 tracks", "meta": ["@dan.test", "Nov 2"]]]
#expect(shown.strip(more)["p"] == ["subtitle": "12 tracks", "meta": ["Nov 2"]])
let profile: JSON = ["c": "Stack", "k": [["c": "Profile", "p": ["name": "Dan", "handle": "dan.test"]]]]
#expect(shown.strip(profile)["k"]?.array?.first?["p"] == ["name": "Dan"])
// Deeper than the top, a header is the view's own.
let deep: JSON = ["c": "Stack", "k": [["c": "Text", "p": ["value": "x"]], ["c": "Header", "p": ["title": "Liked tracks"]]]]
#expect(shown.strip(deep) == deep)
}
}
@Suite struct Actions {
@Test func aRecordIsStampedWhenSent() {
let record: JSON = ["subject": ["uri": "at://did:plc:a/app.bsky.feed.post/1", "cid": "bafy"], "createdAt": ["$now": true]]
let stamped = record.stamped(now: Date(timeIntervalSince1970: 0))
#expect(stamped["createdAt"] == "1970-01-01T00:00:00.000Z")
#expect(stamped["subject"] == record["subject"])
}
@Test func anInputIsStampedWithTextAndTimeAtAnyDepth() {
let input: JSON = [
"convoId": "c1",
"message": ["text": ["$text": true], "parts": [["at": ["$now": true]], ["$text": true]]],
"sentAt": ["$now": true],
// Not a stamp: more than its one key.
"kept": ["$now": true, "also": 1],
]
let stamped = input.stamped(now: Date(timeIntervalSince1970: 0), text: "hello")
#expect(
stamped == [
"convoId": "c1",
"message": ["text": "hello", "parts": [["at": "1970-01-01T00:00:00.000Z"], "hello"]],
"sentAt": "1970-01-01T00:00:00.000Z",
"kept": ["$now": true, "also": 1],
]
)
// With no text given (an Action's call), a `$text` is left as it is.
#expect(input.stamped(now: Date(timeIntervalSince1970: 0))["message"]?["text"] == ["$text": true])
}
/// A `Toggle`'s call is stamped with what it was set to, at any depth,
/// beside the time; with none given, a `$on` is left as it is.
@Test func aTogglesInputIsStampedWithItsNewSetting() {
let input: JSON = [
"key": "includeExif",
"value": ["$on": true],
"prefs": [["name": "exif", "enabled": ["$on": true], "at": ["$now": true]], ["$on": true]],
"kept": ["$on": true, "also": 1],
]
#expect(
input.stamped(now: Date(timeIntervalSince1970: 0), on: false) == [
"key": "includeExif",
"value": false,
"prefs": [["name": "exif", "enabled": false, "at": "1970-01-01T00:00:00.000Z"], false],
"kept": ["$on": true, "also": 1],
]
)
#expect(input.stamped(now: Date(timeIntervalSince1970: 0), on: true)["value"] == true)
#expect(input.stamped(now: Date(timeIntervalSince1970: 0))["value"] == ["$on": true])
}
/// A queued send goes from the throttle's own task uncancelled: URLSession
/// refuses a cancelled task's request, and the server never hears of it.
@MainActor @Test func aQueuedSendGoesUncancelled() async throws {
final class Sends { var cancelled: [Bool] = [] }
let sends = Sends()
let feedback = Interactions { _, interactions in
sends.cancelled.append(Task.isCancelled)
return (interactions.count, nil)
}
feedback.add("at://did:plc:f/app.bsky.feed.generator/f", ["item": "at://did:plc:a/app.bsky.feed.post/1", "event": .string(Interactions.seen)])
for _ in 0..<200 where sends.cancelled.isEmpty { try await Task.sleep(for: .milliseconds(10)) }
#expect(sends.cancelled == [false])
}
@MainActor @Test func anActionsCallIsTrustedTreesOnlyAndCallsCallProcedure() throws {
let (_, root) = try conversation()
let p = try #require(root["items"]?.array?[1]["k"]?.array?[1]["p"])
let found = try #require(ActionSpec(p))
let input: JSON = ["convoId": "c1", "messageId": "m2", "at": ["$now": true]]
#expect(found.request == .call(method: "chat.bsky.convo.updateRead", service: "did:web:api.bsky.chat#bsky_chat", input: input))
let context = ViewContext()
context.onAction = { _ in nil }
#expect(!ActionButton.available(found.request, context))
context.trusted = true
#expect(ActionButton.available(found.request, context))
let call = ActionCall.call(method: "chat.bsky.convo.updateRead", service: "did:web:api.bsky.chat#bsky_chat", input: input).tool
#expect(call.name == "call_procedure")
#expect(JSON.object(call.args) == ["method": "chat.bsky.convo.updateRead", "service": "did:web:api.bsky.chat#bsky_chat", "input": input])
}
@Test func aCountCountsTheAccountsOwnAsItIsDoneAndUndone() {
#expect(ActionButton.shown(8, done: false, startedDone: false) == 8)
#expect(ActionButton.shown(8, done: true, startedDone: false) == 9)
#expect(ActionButton.shown(8, done: true, startedDone: true) == 8)
#expect(ActionButton.shown(8, done: false, startedDone: true) == 7)
}
}
@Suite struct Drawing {
private func time(_ iso: String) -> String? {
let now = Format.date("2026-11-16T12:00:00Z")!
return Format.time(iso, now: now, locale: Locale(identifier: "en_US"), calendar: Calendar(identifier: .gregorian), timeZone: TimeZone(identifier: "UTC")!)?.shown
}
@Test func aTimeIsShortAndItsFullDateIsReadAloud() {
#expect(time("2026-11-16T11:59:30Z") == "now")
#expect(time("2026-11-16T12:00:30Z") == "now")
#expect(time("2026-11-16T12:01:00Z") == "Nov 16")
#expect(time("2026-11-16T11:54:59.123Z") == "5m")
#expect(time("2026-11-16T09:00:00Z") == "3h")
#expect(time("2026-11-14T12:00:00Z") == "2d")
#expect(time("2026-11-09T12:00:00Z") == "Nov 9")
#expect(time("2026-11-17T12:00:00Z") == "Nov 17")
#expect(time("2025-11-15T12:00:00Z") == "Nov 15, 2025")
#expect(time("yesterday") == nil)
let full = Format.time("2025-11-15T15:04:00Z", locale: Locale(identifier: "en_US"), timeZone: TimeZone(identifier: "UTC")!)?.full
#expect(full?.contains("Nov 15, 2025") == true)
#expect(full?.contains("3:04") == true)
}
@Test func aCutRowCutsTheFirstToAFloorThenTheMiddleThenTheFirstNeverTheLast() {
let ideal: [CGFloat] = [100, 80, 10, 20]
let least: [CGFloat] = [10, 10, 10, 20]
func widths(_ room: CGFloat) -> [CGFloat] { Cut.widths(ideal: ideal, least: least, floor: 40, room: room) }
#expect(widths(300) == ideal)
#expect(widths(170) == [60, 80, 10, 20])
#expect(widths(120) == [40, 50, 10, 20])
#expect(widths(60) == [20, 10, 10, 20])
#expect(widths(10) == [10, 10, 10, 20])
#expect(Cut.widths(ideal: [30, 20], least: [5, 5], floor: 40, room: 30) == [10, 20])
}
/// An account's name first in a cut row is kept whole, as the web keeps
/// it: what follows it is cut instead, the last still never.
@Test func aCutRowKeepsANameFirstWholeAndCutsWhatFollows() {
let ideal: [CGFloat] = [100, 80, 10, 20]
let least: [CGFloat] = [10, 10, 10, 20]
func widths(_ room: CGFloat) -> [CGFloat] { Cut.widths(ideal: ideal, least: least, floor: 40, room: room, whole: true) }
#expect(widths(300) == ideal)
#expect(widths(170) == [100, 40, 10, 20])
#expect(widths(120) == [100, 10, 10, 20])
#expect(Resolved.isName(["c": "Link", "p": ["label": "Ann", "style": "name"]]))
#expect(!Resolved.isName(["c": "Link", "p": ["label": "Ann", "style": "name", "current": true]]))
#expect(!Resolved.isName(["c": "Link", "p": ["label": "@ann.test"]]))
#expect(!Resolved.isName(["c": "Text", "p": ["style": "name"]]))
}
/// A search puts what is searched for, trimmed, into its call's params
/// under its param, in place of what was there; nothing, no call.
@Test func aSearchCallsItsOpenWithTheTextAsItsParam() {
let open: JSON = ["call": ["name": "query", "args": ["method": "social.grain.unspecced.searchGalleries", "params": ["q": "cats", "limit": 20]]]]
let call = ResolvedSearch.call(open: open, param: "q", text: " dogs ")
#expect(call == Call("query", ["method": "social.grain.unspecced.searchGalleries", "params": ["q": "dogs", "limit": 20]]))
let bare: JSON = ["call": ["name": "query", "args": ["method": "app.bsky.actor.searchActors"]]]
#expect(ResolvedSearch.call(open: bare, param: "term", text: "ann") == Call("query", ["method": "app.bsky.actor.searchActors", "params": ["term": "ann"]]))
#expect(ResolvedSearch.call(open: open, param: "q", text: " ") == nil)
#expect(ResolvedSearch.call(open: ["url": "https://example.com"], param: "q", text: "dogs") == nil)
}
/// A `Slides`' items as its slides: a call only with its method, service
/// and input; five seconds where it says none; going on past the
/// last, or back before the first, runs off that end; and the pictures
/// loaded ahead, the next two in front, the one it starts from drawn ahead.
@Test func slidesReadTheirItemsAndRunOffTheirEnds() {
let items: [JSON] = [
["src": ["src": "https://cdn.test/a.jpg"], "alt": "A dog", "ratio": .number(0.1), "time": "2026-11-19T10:00:00Z", "place": "Oslo",
"call": ["method": "social.grain.story.markSeen", "service": "did:web:grain.test#grain", "input": ["uri": "at://did:plc:a/social.grain.story/1"]],
"k": [["c": "Menu", "p": ["label": "More"], "k": []]]],
["src": .null, "alt": "", "ratio": .null, "call": ["method": "social.grain.story.markSeen"]],
]
let slides = ResolvedSlides.slides(items)
#expect(slides.count == 2)
#expect(slides[0].source == Source(src: "https://cdn.test/a.jpg", fallback: nil))
#expect(slides[0].alt == "A dog")
#expect(slides[0].place == "Oslo")
#expect(slides[0].call == .call(method: "social.grain.story.markSeen", service: "did:web:grain.test#grain", input: ["uri": "at://did:plc:a/social.grain.story/1"]))
#expect(slides[1].source == nil && slides[1].time == nil && slides[1].call == nil)
// What is drawn over a slide (its ⋯), its own; none where it has none.
#expect(slides[0].k.map { $0["c"]?.string } == ["Menu"])
#expect(slides[1].k.isEmpty)
#expect(ResolvedSlides.seconds(nil) == 5)
#expect(ResolvedSlides.seconds(0) == 5)
#expect(ResolvedSlides.seconds(8) == 8)
#expect(ResolvedSlides.move(0, by: 1, count: 3) == .to(1))
#expect(ResolvedSlides.move(2, by: -1, count: 3) == .to(1))
#expect(ResolvedSlides.move(2, by: 1, count: 3) == .end(.next))
#expect(ResolvedSlides.move(0, by: -1, count: 3) == .end(.previous))
#expect(ResolvedSlides.move(0, by: 1, count: 1) == .end(.next))
// Where it begins: `start`, a whole number from 0, else the first.
#expect(ResolvedSlides.start(nil) == 0)
#expect(ResolvedSlides.start(2) == 2)
#expect(ResolvedSlides.start(.number(-1)) == 0)
#expect(ResolvedSlides.start(.number(1.5)) == 0)
#expect(ResolvedSlides.start("2") == 0)
#expect(ResolvedSlides.ahead(0, count: 4, active: true, start: 0) == [1, 2])
#expect(ResolvedSlides.ahead(2, count: 4, active: true, start: 0) == [3])
#expect(ResolvedSlides.ahead(3, count: 4, active: true, start: 0) == [])
#expect(ResolvedSlides.ahead(1, count: 4, active: false, start: 2) == [2])
#expect(ResolvedSlides.ahead(0, count: 2, active: false, start: 5) == [])
}
/// A text's font with no faces is exactly the system's `Font` it says;
/// with an app's faces, their family at the style's default size,
/// scaled as the style is, monospaced text staying the system's.
@Test func aFontIsTheSystemsWithNoFacesAndTheAppsWithThem() {
let none = Typefaces()
#expect(HUDFont.subheadline.weight(.semibold).font(none) == Font.subheadline.weight(.semibold))
#expect(HUDFont.footnote.monospaced().font(none) == Font.footnote.monospaced())
#expect(HUDFont.caption.monospacedDigit().font(none) == Font.caption.monospacedDigit())
#expect(HUDFont.subheadline.italic().font(none) == Font.subheadline.italic())
#expect(HUDFont.headline.display().font(none) == Font.headline)
#expect(HUDFont.size(.body) == 17)
let grain = Typefaces(body: "Plus Jakarta Sans", display: "Syne")
#expect(HUDFont.subheadline.weight(.semibold).font(grain) == Font.custom("Plus Jakarta Sans", size: HUDFont.size(.subheadline), relativeTo: .subheadline).weight(.semibold))
#expect(HUDFont.headline.font(grain) == Font.custom("Plus Jakarta Sans", size: HUDFont.size(.headline), relativeTo: .headline).weight(.semibold))
#expect(HUDFont.title.display().weight(.heavy).font(grain) == Font.custom("Syne", size: HUDFont.size(.title), relativeTo: .title).weight(.heavy))
#expect(HUDFont.footnote.monospaced().font(grain) == Font.footnote.monospaced())
#expect(HUDFont.body.display().font(Typefaces(body: "Plus Jakarta Sans")) == Font.custom("Plus Jakarta Sans", size: 17, relativeTo: .body))
}
/// What a `Faces` line says: its lead, the names, and how many more past
/// them, in its noun for one or many, else "more".
@Test func facesSayTheirNamesAndHowManyMore() {
let followers = ["follower", "followers"]
let lead = "Followed by"
#expect(ResolvedFaces.words(lead: lead, names: [], count: 0, noun: followers) == "Followed by")
#expect(ResolvedFaces.words(lead: nil, names: [], count: 3, noun: followers) == "3 followers")
#expect(ResolvedFaces.words(lead: lead, names: ["alice"], count: 1, noun: followers) == "Followed by alice")
#expect(ResolvedFaces.words(lead: lead, names: ["alice", "bob"], count: 2, noun: followers) == "Followed by alice, bob")
#expect(ResolvedFaces.words(lead: lead, names: ["alice", "bob"], count: 3, noun: followers) == "Followed by alice, bob and 1 follower")
#expect(ResolvedFaces.words(lead: lead, names: ["alice", "bob"], count: 7, noun: followers) == "Followed by alice, bob and 5 followers")
#expect(ResolvedFaces.words(lead: lead, names: ["alice"], count: 4, noun: nil) == "Followed by alice and 3 more")
#expect(ResolvedFaces.words(lead: "Followed by ", names: ["alice"], count: 1, noun: nil) == "Followed by alice")
#expect(ResolvedFaces.words(lead: nil, names: ["alice", "bob"], count: 2, noun: nil) == "alice, bob")
// From the tree: the first two faces' names, the nouns one and many.
let p: JSON = [
"faces": [["src": .null, "name": "alice"], ["src": .null, "name": "bob"], ["src": .null]],
"count": 5, "lead": "Followed by", "countNoun": ["one": "other you follow", "many": "others you follow"],
]
#expect(ResolvedFaces.said(p) == "Followed by alice, bob and 3 others you follow")
}
/// A `Panes`' panes are its labelled `Pane` children, in order; each
/// icon the server names is a symbol, filled where it has a filled form
/// and is chosen; a page more grows the Covers inside a pane.
@Test func panesAreTheirLabelledPanesAndPageInside() throws {
let covers: JSON = ["c": "Covers", "p": ["style": "tiles", "page": true], "items": [["src": "a"]]]
let panes: JSON = ["c": "Panes", "k": [
["c": "Pane", "p": ["label": "Galleries", "icon": "grid"], "k": [covers]],
["c": "Text", "p": ["runs": []]],
["c": "Pane", "p": ["icon": "heart"], "k": []],
["c": "Pane", "p": ["label": "Stories", "icon": "clock"], "k": []],
]]
let found = ResolvedPanes.panes(panes)
#expect(found.map(\.label) == ["Galleries", "Stories"])
#expect(found.map(\.icon) == ["grid", "clock"])
#expect(ResolvedPanes.symbol("grid", chosen: false) == "square.grid.3x3")
#expect(ResolvedPanes.symbol("grid", chosen: true) == "square.grid.3x3.fill")
#expect(ResolvedPanes.symbol("heart", chosen: true) == "heart.fill")
#expect(ResolvedPanes.symbol("clock", chosen: false) == "clock")
#expect(ResolvedPanes.symbol("clock", chosen: true) == "clock.fill")
#expect(ResolvedPanes.symbol("feed", chosen: false) == "photo.on.rectangle")
#expect(ResolvedPanes.symbol("people", chosen: false) == "person.2")
#expect(ResolvedPanes.symbol("photo", chosen: false) == nil)
#expect(ResolvedPanes.symbol(nil, chosen: true) == nil)
let first = Drawn.tree(["v": 1, "root": ["c": "Stack", "k": [panes]], "next": ["name": "query", "args": [:]]])
let more = Drawn.tree(["v": 1, "root": ["c": "Stack", "k": [["c": "Panes", "k": [["c": "Pane", "p": ["label": "Galleries"], "k": [["c": "Covers", "p": ["page": true], "items": [["src": "b"]]]]]]]]]])
let grown = try #require(first.appending(more))
guard case .tree(let ui) = grown else {
Issue.record("Not a tree")
return
}
#expect(ui["root"]?["k"]?.array?.first?["k"]?.array?.first?["k"]?.array?.first?["items"]?.array?.count == 2)
#expect(ui["next"] == nil)
}
/// A Panes' pager: as tall as the two pages a swipe is between, blended
/// by how far, none until both are measured; the pane shown the nearest,
/// written only as it changes; one picking holds it still.
@MainActor @Test func panesPagerFollowsTheSwipe() {
let heights: [Int: CGFloat] = [0: 300, 1: 100, 2: 200]
#expect(PanesPager.height(heights, progress: 0, count: 3) == 300)
#expect(PanesPager.height(heights, progress: 0.25, count: 3) == 250)
#expect(PanesPager.height(heights, progress: 1.5, count: 3) == 150)
#expect(PanesPager.height(heights, progress: 5, count: 3) == 200)
#expect(PanesPager.height([0: 300], progress: 0.5, count: 3) == nil)
#expect(PanesPager.between(-1, 3) == (0, 1, 0))
let pager = PanesPager()
pager.scrolled(to: 300, count: 3)
#expect(pager.shown == 0)
pager.width = 400
pager.scrolled(to: 300, count: 3)
#expect(pager.shown == 1)
#expect(pager.progress(3) == 0.75)
#expect(!pager.picking(3))
pager.end(2).picking = true
#expect(pager.picking(3))
#expect(pager.end(2) === pager.end(2))
}
/// An open with `sheet` goes to the app's sheet where it shows sheets,
/// else as any call; one without, as any call.
@MainActor @Test func aSheetOpenGoesToTheSheet() throws {
let comments: JSON = ["call": ["name": "query", "args": ["method": "social.grain.comment.getComments"]], "sheet": true]
let view = ViewContext()
var called: [String] = []
view.onCall = { call, _ in called.append("call \(call.args["method"]?.string ?? "")") }
try #require(view.opener(tree: comments)).run()
view.onSheet = { call in called.append("sheet \(call.args["method"]?.string ?? "")") }
try #require(view.opener(tree: comments)).run()
var plain = comments
if case .object(var o) = plain { o["sheet"] = nil; plain = .object(o) }
try #require(view.opener(tree: plain)).run()
#expect(called == ["call social.grain.comment.getComments", "sheet social.grain.comment.getComments", "call social.grain.comment.getComments"])
}
/// An open the app alone does (`{host}`, Sign out) goes to `onHost`,
/// where the app does it; elsewhere, or for an act it does not know,
/// it opens nothing and what opens it is not drawn.
@MainActor @Test func aHostOpenGoesToTheApp() throws {
let signOut: JSON = ["host": "signOut"]
let unknown: JSON = ["host": "deleteAccount"]
let page: JSON = ["url": "https://grain.social/settings/import"]
let view = ViewContext()
#expect(view.opener(tree: signOut) == nil)
#expect(view.unhosted(signOut) && view.unhosted(unknown) && !view.unhosted(page) && !view.unhosted(nil))
var asked: [Hosted] = []
view.onHost = { asked.append($0) }
let open = try #require(view.opener(tree: signOut))
#expect(open.label == "Sign out")
open.run()
#expect(asked == [.signOut])
#expect(!view.unhosted(signOut) && view.unhosted(unknown))
#expect(view.opener(tree: unknown) == nil)
}
/// An `Accounts` draws its children where the app keeps no accounts;
/// where it does, a row each, in its order, named by name, else handle,
/// else DID, the current one marked, switching and adding through the app.
@MainActor @Test func accountsDrawTheAppsAccountsElseTheChildren() {
let view = ViewContext()
#expect(ResolvedAccounts.accounts(view) == nil)
var asked: [String] = []
view.accounts = HostAccounts(
list: [
HostAccount(did: "did:plc:a", handle: "alice.test", name: "Alice", picture: "https://cdn.test/a.jpg"),
HostAccount(did: "did:plc:b", handle: "bob.test", picture: "ftp://nope"),
HostAccount(did: "did:plc:c", name: ""),
],
current: "did:plc:b",
use: { asked.append("use \($0)") },
add: { asked.append("add") }
)
let accounts = ResolvedAccounts.accounts(view)!
let rows = ResolvedAccounts.rows(accounts)
#expect(rows == [
.init(did: "did:plc:a", label: "Alice", handleLine: "@alice.test", picture: "https://cdn.test/a.jpg", current: false),
.init(did: "did:plc:b", label: "bob.test", handleLine: "@bob.test", picture: nil, current: true),
.init(did: "did:plc:c", label: "did:plc:c", handleLine: nil, picture: nil, current: false),
])
accounts.use(rows[0].did)
accounts.add()
#expect(asked == ["use did:plc:a", "add"])
// Rows the app reads later draw as they come: setting the accounts is observed.
final class Changed: @unchecked Sendable { var yes = false }
let changed = Changed()
withObservationTracking { _ = view.accounts } onChange: { changed.yes = true }
view.accounts = nil
#expect(changed.yes)
#expect(ResolvedAccounts.accounts(view) == nil)
}
/// A slide's children: its Menus at the end of its top row, the rest at
/// its bottom-right, a Stack's in its place; the top row's 44 points
/// each, the last pulled 8 in.
@Test func aSlidesMenusEndItsTopRowTheRestItsFoot() {
let comments: JSON = ["c": "Link", "p": ["icon": "comment", "label": "Comments"]]
let like: JSON = ["c": "Action", "p": ["icon": "heart", "label": "Favorite"]]
let menu: JSON = ["c": "Menu", "k": []]
#expect(ResolvedSlides.parts([["c": "Stack", "k": [comments, like]], menu]) == .init(menus: [menu], rest: [comments, like]))
#expect(ResolvedSlides.parts([menu]) == .init(menus: [menu], rest: []))
#expect(ResolvedSlides.parts([["c": "Stack", "k": [menu]]]) == .init(menus: [menu], rest: []))
#expect(ResolvedSlides.parts([["c": "Stack", "k": []]]) == .init(menus: [], rest: []))
#expect(ResolvedSlides.topRowWidth(0) == 0)
#expect(ResolvedSlides.topRowWidth(1) == 36)
#expect(ResolvedSlides.topRowWidth(2) == 80)
}
/// A Panes' row holds the one control its shown pane put there; only
/// what put it there takes it away, so a pane's Covers going as the next
/// one's comes leaves the new one's Select.
@MainActor @Test func aPanesRowKeepsTheControlOfThePaneShown() {
let end = PaneEnd()
let (old, new) = (UUID(), UUID())
var ran = 0
end.control = .init(label: "Select", owner: new) { ran += 1 }
end.clear(old)
#expect(end.control?.label == "Select")
end.control?.run()
#expect(ran == 1)
end.clear(new)
#expect(end.control == nil)
}
/// Covers' select asks once with its action, count and noun, then calls
/// its procedure for each picked in turn, each with its own input; those
/// that failed are left picked, with what went wrong.
@MainActor @Test func pickedCoversAreEachCalledForAndThoseThatFailedLeft() async {
let select: JSON = ["label": "Select", "action": "Delete", "one": "gallery", "many": "galleries", "method": "social.grain.unspecced.deleteGallery", "service": "did:web:grain.social#grain_appview"]
#expect(CoversPick.question(select, count: 1) == "Delete 1 gallery?")
#expect(CoversPick.question(select, count: 3) == "Delete 3 galleries?")
#expect(CoversPick.question(["action": "Hide"], count: 2) == "Hide 2?")
let items: [JSON] = [["pick": ["rkey": "3a"]], ["pick": ["rkey": "3b"]], ["pick": ["rkey": "3c"]]]
struct Refused: LocalizedError { var errorDescription: String? { "Gallery not found" } }
var sent: [String] = []
var progress: [Int] = []
let (left, failure) = await CoversPick.run(select, items: items, picked: [2, 0], act: { call in
guard case .call(let method, let service, let input) = call else { return nil }
#expect(method == "social.grain.unspecced.deleteGallery" && service == "did:web:grain.social#grain_appview")
let rkey = input["rkey"]?.string ?? ""
sent.append(rkey)
if rkey == "3c" { throw Refused() }
return nil
}, progress: { progress.append($0) })
#expect(sent == ["3c", "3a"])
#expect(progress == [1, 2])
#expect(left == [2])
#expect(failure == "Gallery not found")
}
/// A form's field is read aloud by its label, else its placeholder, else
/// its name; a long form (more than two fields, a photos field with a
/// current picture, or one of one photo, drawn large) opens at full
/// height.
@Test func aComposeFieldsSpokenNameAndAFormsHeight() {
let name = ComposeField(p: ["name": "displayName", "kind": "line", "label": "Display name", "placeholder": "", "value": "chad"])
let bio = ComposeField(p: ["name": "description", "kind": "text", "placeholder": "Tell us about yourself"])
let bare = ComposeField(p: ["name": "title", "kind": "line", "label": ""])
let avatar = ComposeField(p: ["name": "avatar", "kind": "photos", "label": "Avatar", "picture": ["src": "https://cdn.test/me.jpg"]])
let photos = ComposeField(p: ["name": "photos", "kind": "photos"])
#expect(name.spoken == "Display name")
#expect(bio.spoken == "Tell us about yourself")
#expect(bare.spoken == "title")
#expect(ComposeField.opensTall([avatar, name]))
#expect(ComposeField.opensTall([name, bio, photos]))
#expect(!ComposeField.opensTall([bio]))
#expect(!ComposeField.opensTall([photos, bio]))
let story = ComposeField(p: ["name": "photos", "kind": "photos", "max": 1])
let round = ComposeField(p: ["name": "avatar", "kind": "photos", "max": 1, "round": true])
#expect(story.single && !round.single && !photos.single)
#expect(ComposeField.opensTall([story, bio]))
#expect(!ComposeField.opensTall([round, bio]))
}
/// A carousel's frame is its tallest picture's, ratios kept between 1:4
/// and 4:1 and none square, never taller than 9:16; its dots are at most
/// five around the one showing, smaller and fainter further off, and
/// none for one picture.
@Test func aCarouselsFrameAndDots() {
let wide: JSON = ["ratio": .number(1.5)]
let tall: JSON = ["ratio": .number(0.8)]
let none: JSON = ["ratio": .null]
#expect(ResolvedGallery.frame([wide]) == 1.5)
#expect(ResolvedGallery.frame([wide, tall]) == 0.8)
#expect(ResolvedGallery.frame([wide, none]) == 1)
#expect(ResolvedGallery.frame([["ratio": .number(0.3)]]) == 9.0 / 16.0)
#expect(ResolvedGallery.frame([["ratio": .number(10)]]) == 4)
#expect(ResolvedGallery.dots(at: 0, count: 1).isEmpty)
#expect(ResolvedGallery.dots(at: 0, count: 3).map(\.index) == [0, 1, 2])
#expect(ResolvedGallery.dots(at: 0, count: 8).map(\.index) == [0, 1, 2, 3, 4])
#expect(ResolvedGallery.dots(at: 4, count: 8).map(\.index) == [2, 3, 4, 5, 6])
#expect(ResolvedGallery.dots(at: 7, count: 8).map(\.index) == [3, 4, 5, 6, 7])
let around = ResolvedGallery.dots(at: 0, count: 8)
#expect(around.map(\.size) == [6, 6, 4, 3, 3])
#expect(around.map(\.opacity) == [1, 0.4, 0.3, 0.2, 0.2])
}
/// A shelf card's parts are its children, or those of the one Stack it
/// holds, so its last (a Follow) stands at its foot.
@Test func aShelfCardsPartsEndWithItsFoot() {
let face: JSON = ["c": "Image", "p": [:]]
let name: JSON = ["c": "Text", "p": [:]]
let follow: JSON = ["c": "Action", "p": [:]]
#expect(ResolvedList.shelfParts(["k": [face, name, follow]]) == [face, name, follow])
#expect(ResolvedList.shelfParts(["k": [["c": "Stack", "k": [face, name, follow]]]]) == [face, name, follow])
let row: JSON = ["c": "Row", "k": [face, name]]
#expect(ResolvedList.shelfParts(["k": [row]]) == [row])
#expect(ResolvedList.shelfParts(["k": [["c": "Stack", "k": [face]], follow]]).count == 2)
#expect(ResolvedList.shelfParts([:]).isEmpty)
}
/// A row Action joins the rows before it, a List's or another row
/// Action's, drawing the line between rows above it; after anything
/// else it draws none.
@Test func aRowActionJoinsTheRowsBeforeIt() {
#expect(ResolvedChildren.rows(["c": "List", "p": [:]]))
#expect(ResolvedChildren.rows(["c": "List", "p": ["style": "rows"]]))
#expect(!ResolvedChildren.rows(["c": "List", "p": ["style": "cards"]]))
#expect(ResolvedChildren.rows(["c": "Action", "p": ["style": "row"]]))
#expect(!ResolvedChildren.rows(["c": "Action", "p": ["style": "button"]]))
#expect(!ResolvedChildren.rows(["c": "Text", "p": [:]]))
}
/// Rows with `chevrons` end with a chevron where they open something; no other style does.
@Test func rowsWithChevronsEndWithOne() {
#expect(ResolvedList.chevrons(["style": "rows", "chevrons": true]))
#expect(ResolvedList.chevrons(["chevrons": true]))
#expect(!ResolvedList.chevrons(["style": "rows"]))
#expect(!ResolvedList.chevrons(["style": "cards", "chevrons": true]))
}
/// A `pages` list's item opens with the calls its list's items open, in
/// order, those whose open is a call alone, and which of them it is; an
/// item whose open is no call opens none.
@Test func aPagesListOpensWithItsItemsCalls() {
let stories = { (did: String) -> JSON in
["open": ["call": ["name": "query", "args": ["method": "social.grain.story.getStories", "params": ["actor": .string(did)]]]], "k": []]
}
let call = { (did: String) in Call("query", ["method": "social.grain.story.getStories", "params": ["actor": .string(did)]]) }
let items: [JSON] = [stories("did:plc:a"), ["open": ["url": "https://grain.social"], "k": []], ["k": []], stories("did:plc:b"), stories("did:plc:c")]
#expect(ResolvedList.pages(items, opened: 0) == Pages(calls: [call("did:plc:a"), call("did:plc:b"), call("did:plc:c")], at: 0))
#expect(ResolvedList.pages(items, opened: 3)?.at == 1)
#expect(ResolvedList.pages(items, opened: 4)?.at == 2)
#expect(ResolvedList.pages(items, opened: 1) == nil)
#expect(ResolvedList.pages(items, opened: 2) == nil)
// One's own Your story, opening at its form: in its own pager first, in no other's.
let yours: JSON = ["open": ["call": ["name": "query", "args": ["method": "social.grain.story.getStories", "params": ["actor": "did:plc:me"], "compose": true]]], "k": []]
let mine = Call("query", ["method": "social.grain.story.getStories", "params": ["actor": "did:plc:me"], "compose": true])
let strip = [yours] + items
#expect(ResolvedList.pages(strip, opened: 0) == Pages(calls: [mine, call("did:plc:a"), call("did:plc:b"), call("did:plc:c")], at: 0))
#expect(ResolvedList.pages(strip, opened: 1) == Pages(calls: [call("did:plc:a"), call("did:plc:b"), call("did:plc:c")], at: 0))
// With stories of one's own its call has no `compose`: a page as any other, the first.
let withStories: JSON = ["open": ["call": ["name": "query", "args": ["method": "social.grain.story.getStories", "params": ["actor": "did:plc:me"]]]], "k": []]
let own = Call("query", ["method": "social.grain.story.getStories", "params": ["actor": "did:plc:me"]])
#expect(ResolvedList.pages([withStories] + items, opened: 1) == Pages(calls: [own, call("did:plc:a"), call("did:plc:b"), call("did:plc:c")], at: 1))
}
/// A screen opened at its form (the `Compose` marked `open`, not a
/// Menu's row) opens at it; one with stories, or only a Menu's, doesn't.
@Test func aScreenOpensAtTheFormMarkedOpen() {
let compose = { (open: Bool) -> JSON in ["c": "Compose", "p": open ? ["label": "Add", "open": true] : ["label": "Add"]] }
let tree = { (k: [JSON]) in Drawn.tree(["v": 1, "root": ["c": "Stack", "k": .array(k)]]) }
#expect(tree([["c": "Slides", "k": [compose(true)]]]).opensAtForm)
#expect(tree([["c": "Slides", "k": [compose(true)]]]).openedForm?["label"] == "Add")
#expect(!tree([["c": "Slides", "k": [compose(false)]]]).opensAtForm)
#expect(!tree([["c": "Menu", "k": [compose(true)]]]).opensAtForm)
#expect(!Drawn.error("no").opensAtForm)
}
/// An action with `leave` closes its screen once it has written, one
/// with `reload` reads the tree again, one with both leaves; none of
/// them when the write fails or undoes, and one with neither does
/// nothing more.
@MainActor @Test func anActionThatLeavesOrReloadsDoesOnceItHasWritten() async throws {
let uri = "at://did:plc:a/social.grain.gallery/1"
let delete: JSON = ["label": "Delete", "delete": ["uri": .string(uri)]]
let spec = try #require(ActionSpec(delete.merged(with: ["confirm": "Delete this gallery?", "tone": "danger", "leave": true])))
#expect(spec.leave && !spec.reload && spec.danger && spec.confirm == "Delete this gallery?")
let stays = try #require(ActionSpec(delete))
#expect(!stays.leave && !stays.reload)
let reloads = try #require(ActionSpec(delete.merged(with: ["reload": true])))
#expect(reloads.reload && !reloads.leave)
let both = try #require(ActionSpec(delete.merged(with: ["reload": true, "leave": true])))
let view = ViewContext()
var left = 0
var read = 0
view.onLeave = { left += 1 }
view.onReload = { read += 1 }
view.onAction = { _ in nil }
func send(_ spec: ActionSpec, from run: ActionRun = ActionRun()) async -> ActionRun {
run.send(.write(.delete(uri: uri)), spec, view)
var turns = 0
while run.busy, turns < 1000 {
await Task.yield()
turns += 1
}
return run
}
_ = await send(spec)
#expect(left == 1 && read == 0)
_ = await send(stays)
#expect(left == 1 && read == 0)
_ = await send(reloads)
#expect(left == 1 && read == 1)
_ = await send(both)
#expect(left == 2 && read == 1)
// An undo (a create's record deleted again) neither leaves nor reads again.
_ = await send(reloads, from: ActionRun(ran: Ran(done: true, made: uri)))
#expect(left == 2 && read == 1)
view.onAction = { _ in throw HUDError.tool("No.") }
let failing = await send(both)
#expect(left == 2 && read == 1 && failing.error == "No.")
}
/// A Link with `share` (an https URL) shares that page rather than
/// opening anything, as a menu's row too, open or not; any other URL is
/// no share.
@MainActor @Test func aLinkWithShareSharesItsPage() {
let profile = "https://grain.social/profile/chadtmiller.com"
#expect(Resolved.share(["label": "Share profile", "share": .string(profile)]) == URL(string: profile))
#expect(Resolved.share(["label": "Share", "share": "http://grain.social/profile/a"]) == nil)
#expect(Resolved.share(["label": "Share", "share": "javascript:alert(1)"]) == nil)
#expect(Resolved.share(["label": "Share"]) == nil)
let view = ViewContext()
view.onCall = { _, _ in }
let rows = ResolvedMenu.rows([
["c": "Link", "p": ["label": "Share profile", "share": .string(profile)]],
["c": "Link", "p": ["label": "Open", "open": ["call": ["name": "describe_repo", "args": [:]]], "share": .string(profile)]],
["c": "Link", "p": ["label": "Nowhere"]],
], view)
#expect(rows == [.share("Share profile", URL(string: profile)!), .share("Open", URL(string: profile)!)])
}
/// A Link with `copy` copies that text rather than opening anything, as
/// a menu's row too; one without opens what it opens.
@MainActor @Test func aLinkWithCopyCopiesItsText() {
#expect(Resolved.copy(["label": "Copy handle", "copy": "@chadtmiller.com"]) == "@chadtmiller.com")
#expect(Resolved.copy(["label": "Copy handle"]) == nil)
let view = ViewContext()
view.onCall = { _, _ in }
let open: JSON = ["call": ["name": "describe_repo", "args": [:]]]
let rows = ResolvedMenu.rows([
["c": "Link", "p": ["label": "Copy handle", "copy": "@chadtmiller.com"]],
["c": "Link", "p": ["label": "Open", "open": open]],
], view)
#expect(rows == [.copy("Copy handle", "@chadtmiller.com"), .link("Open", open)])
}
/// A menu's rows are its actions, links and forms the app acts on here,
/// in order; the rest left out. An action says what it asks first, and
/// whether it is dangerous.
@MainActor @Test func aMenusRowsAreWhatTheAppActsOnHere() throws {
let delete: JSON = ["label": "Delete", "delete": ["uri": "at://did:plc:a/social.grain.gallery/1"], "confirm": "Delete this gallery?", "tone": "danger"]
let open: JSON = ["call": ["name": "get_record", "args": ["uri": "at://did:plc:a/social.grain.gallery/1"]]]
let edit: JSON = ["label": "Edit", "fields": [["name": "title", "kind": "line"]], "writes": []]
let k: [JSON] = [
["c": "Action", "p": delete],
["c": "Action", "p": ["label": "Mark read", "call": ["method": "m", "service": "s", "input": [:]]]],
["c": "Link", "p": ["label": "Open", "open": open]],
["c": "Link", "p": ["label": "Here", "open": open, "current": true]],
["c": "Compose", "p": edit],
["c": "Text", "p": ["runs": [["text": "x"]]]],
]
let context = ViewContext()
#expect(ResolvedMenu.rows(k, context).isEmpty)
context.onAction = { _ in nil }
context.onCall = { _, _ in }
context.onTool = { _ in [:] }
let spec = try #require(ActionSpec(delete))
#expect(spec.confirm == "Delete this gallery?" && spec.danger)
#expect(ResolvedMenu.rows(k, context) == [.action(spec), .link("Open", open), .compose(edit)])
context.trusted = true
#expect(ResolvedMenu.rows(k, context).count == 4)
}
/// Grain's profile ⋯ on someone else's, as the server resolves it (the
/// fixture hud-core's test holds to): Share profile, Copy handle, Mute,
/// Block and Report, every one a row; and the same rows where they come
/// in Stacks within Stacks, as an older server sent Mute.
@MainActor @Test func grainsProfileMenuHasEveryRowThroughItsStacks() throws {
let url = try #require(Bundle.module.url(forResource: "ui-menu", withExtension: "json", subdirectory: "Fixtures"))
let menu = try JSONDecoder().decode(JSON.self, from: Data(contentsOf: url))
let context = ViewContext()
context.trusted = true
context.onAction = { _ in nil }
context.onCall = { _, _ in }
context.onTool = { _ in [:] }
let words: ([MenuRow]) -> [String] = { rows in
rows.map { row in
switch row {
case .action(let spec): spec.label
case .link(let label, _), .share(let label, _), .copy(let label, _): label
case .compose(let p): p.str("label") ?? ""
}
}
}
let k = menu["k"]?.array ?? []
#expect(words(ResolvedMenu.rows(k, context)) == ["Share profile", "Copy handle", "Mute", "Block", "Report"])
let nested: [JSON] = Array(k.prefix(2)) + [["c": "Stack", "k": [["c": "Stack", "k": [k[2]]], k[3], ["c": "Stack", "k": [k[4]]]]]]
#expect(ResolvedMenu.rows(nested, context) == ResolvedMenu.rows(k, context))
}
/// A tree's `Bar` at its top (it, or first among its `Stack`'s) is lifted
/// out for the navigation bar, holding the kinds a bar holds; a link's
/// icon is its symbol.
@Test func theBarAtATreesTopIsLiftedOutAndALinksIconIsItsSymbol() {
let bar: JSON = ["c": "Bar", "k": [
["c": "Link", "p": ["label": "Settings", "icon": "settings"]],
["c": "Text", "p": ["runs": [["text": "x"]]]],
["c": "Menu", "p": ["label": "More"], "k": []],
]]
let header: JSON = ["c": "Header", "p": ["title": "Grain"]]
let lifted = ResolvedBar.lift(["c": "Stack", "k": [header, bar]])
#expect(lifted.root == ["c": "Stack", "k": [header]])
#expect(lifted.bar == bar)
#expect(ResolvedBar.lift(bar).root == .null)
#expect(ResolvedBar.lift(header).bar == nil)
// Home's: the strip first, the Bar inside Stacks shown only on the feed itself.
let strip: JSON = ["c": "Stack", "k": [header]]
let nested = ResolvedBar.lift(["c": "Stack", "k": [strip, ["c": "Stack", "p": ["gap": "sm"], "k": [["c": "Stack", "k": [bar]]]], header]])
#expect(nested.bar == bar)
#expect(nested.root == ["c": "Stack", "k": [strip, header]])
let beside = ResolvedBar.lift(["c": "Stack", "k": [strip, ["c": "Stack", "k": [bar, header]]]])
#expect(beside.root == ["c": "Stack", "k": [strip, ["c": "Stack", "k": [header]]]])
// Only Stacks are looked into.
#expect(ResolvedBar.lift(["c": "Stack", "k": [["c": "Row", "k": [bar]]]]).bar == nil)
#expect(ResolvedBar.lift(["c": "Stack", "k": [strip]]).bar == nil)
#expect(ResolvedBar.items(bar).map { $0["c"]?.string } == ["Link", "Menu"])
// A profile's Settings, in a Stack kept only on one's own (`mine`): its buttons in the bar.
let own: JSON = ["c": "Bar", "k": [
["c": "Stack", "k": [["c": "Link", "p": ["label": "Settings", "icon": "settings"]]]],
["c": "Menu", "p": ["label": "More"], "k": []],
]]
#expect(ResolvedBar.items(own).map { $0["p"]?["label"]?.string } == ["Settings", "More"])
// A screen's title alone (a list of followers'): lifted out all the same, holding no buttons.
let titled: JSON = ["c": "Bar", "p": ["title": "Followers"]]
let list: JSON = ["c": "List", "p": ["style": "rows"]]
let alone = ResolvedBar.lift(["c": "Stack", "k": [titled, list]])
#expect(alone.bar?["p"]?["title"]?.string == "Followers")
#expect(alone.root == ["c": "Stack", "k": [list]])
#expect(ResolvedBar.items(titled).isEmpty)
#expect(Icons.symbol("settings") == .system("gearshape"))
#expect(Icons.symbol("plus") == .system("plus"))
#expect(Icons.symbol("search") == .system("magnifyingglass"))
#expect(Icons.symbol("compass") == .system("safari"))
#expect(Icons.symbol("notification") == .system("bell"))
#expect(Icons.symbol("people") == .system("person.2"))
}
}
@Suite struct Lead {
/// A place's map at the head of its feed meets the bar: no padding over it.
@Test func aBleedingMapFirstLeadsTheScreen() {
let map: JSON = ["c": "Map", "p": ["bleed": true]]
let title: JSON = ["c": "Text", "p": [:]]
#expect(Drawn.tree(["root": ["c": "Stack", "k": [["c": "Stack", "k": [map, title]]]]]).leadsWithBleed)
#expect(!Drawn.tree(["root": ["c": "Stack", "k": [title, map]]]).leadsWithBleed)
#expect(!Drawn.tree(["root": ["c": "Map", "p": [:]]]).leadsWithBleed)
}
/// A camera's feed, its Bar lifted into the navigation bar, starts with
/// tiles: they meet the bar as they meet the sides.
@Test func tilesUnderALiftedBarLeadTheScreen() {
let bar: JSON = ["c": "Bar", "p": ["title": "Canon EOS 650D"]]
let tiles: JSON = ["c": "Covers", "p": ["style": "tiles"]]
let feed = Drawn.tree(["root": ["c": "Stack", "k": [["c": "Stack", "k": [bar, tiles]]]]])
#expect(feed.leadsWithBleed)
// A tile draws its Bar in its place, over the tiles.
#expect(!feed.leadsTileWithBleed)
#expect(Drawn.tree(["root": tiles]).leadsTileWithBleed)
// Cards keep their inset, and so do tiles with Select over them.
#expect(!Drawn.tree(["root": ["c": "Covers", "p": [:]]]).leadsWithBleed)
#expect(!Drawn.tree(["root": ["c": "Covers", "p": ["style": "tiles", "select": ["label": "Select"]]]]).leadsWithBleed)
}
}
@Suite struct Messages {
@Test func aConversationIsDrawnOldestFirstInRuns() throws {
let (drawn, root) = try conversation()
#expect(drawn.pagesItself)
#expect(drawn.nextPage?.args["cursor"] == "m0")
#expect(root["p"]?["group"] == true)
#expect(root["p"]?["send"]?["input"]?["message"]?["text"] == ["$text": true])
let rows = Conversation.rows(root)
#expect(rows.map(\.id) == ["m3", "m2", "m1", "m0"])
// A note of the conversation's own: no sender.
#expect(rows[0].from == nil && !rows[0].mine)
// Two of theirs a minute apart: one run, its face and time by the last.
#expect(rows[1].from == "did:plc:you" && rows[1].first && !rows[1].last)
#expect(!rows[2].first && rows[2].last)
#expect(rows[2].who?["avatar"]?["src"] == "https://cdn.bsky.app/img/avatar_thumbnail/plain/you@jpeg")
#expect(rows[2].k.count == 2)
#expect(rows[3].mine && rows[3].first && rows[3].last && rows[3].at == "2026-11-16T09:20:00.000Z")
// What was sent, before the tree is read again: the person's own, after the rest.
let sent = Conversation.rows(root, pending: [.init(text: "ok", at: "2026-11-16T09:21:00.000Z")])
#expect(sent.count == 5)
#expect(sent[4].mine && sent[4].pending && !sent[4].first && sent[4].last && !sent[3].last)
#expect(sent[4].k == [["c": "Text", "p": ["runs": [["text": "ok"]]]]])
}
@Test func oneSendersBubblesMoreThanFiveMinutesApartAreTwoRuns() {
let item = { (at: String) -> JSON in ["from": "did:plc:you", "at": .string(at), "k": [["c": "Text", "p": ["runs": [["text": "x"]]]]]] }
let node: JSON = ["c": "Messages", "p": ["group": false], "items": [item("2026-11-16T09:00:00Z"), item("2026-11-16T09:05:01Z")]]
let rows = Conversation.rows(node)
#expect(rows.map(\.id) == ["m0", "m1"])
#expect(rows[0].first && rows[0].last && rows[1].first && rows[1].last)
}
@Test func aPageMoreAddsEarlierMessagesAboveKeepingWhatWasThere() throws {
let (drawn, root) = try conversation()
let grown = try #require(drawn.appending(drawn))
guard case .tree(let ui) = grown else { return }
let rows = Conversation.rows(try #require(ui["root"]))
// The earlier page above; what was drawn keeps its ids, so the scroll holds on it.
#expect(rows.map(\.id) == ["m7", "m6", "m5", "m4", "m3", "m2", "m1", "m0"])
#expect(Array(rows.suffix(4)) == Conversation.rows(root))
}
@Test func aReturnTypedSendsButALineInAPasteDoesNot() {
#expect(Conversation.returned(from: "hi", to: "hi\n") == "hi")
#expect(Conversation.returned(from: "hi", to: "h\ni") == "hi")
#expect(Conversation.returned(from: "", to: "\n") == "")
#expect(Conversation.returned(from: "", to: "a\nb") == nil)
#expect(Conversation.returned(from: "hi", to: "hi!") == nil)
#expect(Conversation.returned(from: "hi\n", to: "hi") == nil)
}
}
@Suite struct SignIn {
let server = AuthServer(
issuer: "https://hud.example",
authorizationEndpoint: URL(string: "https://hud.example/oauth/authorize")!,
tokenEndpoint: URL(string: "https://hud.example/oauth/token")!,
revocationEndpoint: nil
)
private func back(_ query: String) -> URL {
URL(string: "place.hud.app:/oauth/callback?\(query)")!
}
@Test func theCodeComesBackOnlyForThisRequestFromThisServer() throws {
let request = SignInRequest(server: server)
let iss = "iss=https%3A%2F%2Fhud.example"
#expect(try request.code(from: back("code=c1&state=\(request.state)&\(iss)")) == "c1")
#expect(throws: SignInError.self) { try request.code(from: back("code=c1&state=other&\(iss)")) }
#expect(throws: SignInError.self) { try request.code(from: back("code=c1&state=\(request.state)&iss=https%3A%2F%2Fevil.example")) }
#expect(throws: SignInError.self) { try request.code(from: back("code=c1&state=\(request.state)")) }
#expect(throws: SignInError.self) { try request.code(from: URL(string: "com.evil.app:/oauth/callback?code=c1&state=\(request.state)&\(iss)")!) }
#expect(throws: SignInError.refused("You said no")) {
try request.code(from: back("error=access_denied&error_description=You+said+no&state=\(request.state)&\(iss)"))
}
}
@Test func theRequestAsksForThisAppWithItsChallenge() throws {
let request = SignInRequest(server: server)
let asked = Form.decode(try #require(URLComponents(url: request.url, resolvingAgainstBaseURL: false)?.percentEncodedQuery))
#expect(asked["client_id"] == "https://hud.example/oauth/app-client.json")
#expect(asked["redirect_uri"] == "place.hud.app:/oauth/callback")
#expect(asked["resource"] == "https://hud.example/mcp")
#expect(asked["code_challenge_method"] == "S256")
#expect(asked["code_challenge"] == request.challenge)
#expect(asked["state"] == request.state)
#expect(asked["login_hint"] == nil)
}
@Test func aHandleTypedGoesAsTheLoginHint() throws {
let request = SignInRequest(server: server, hint: "alice.bsky.social")
let asked = Form.decode(try #require(URLComponents(url: request.url, resolvingAgainstBaseURL: false)?.percentEncodedQuery))
#expect(asked["login_hint"] == "alice.bsky.social")
#expect(asked["client_id"] == "https://hud.example/oauth/app-client.json")
#expect(SignInRequest(server: server, hint: "").hint == nil)
}
@Test func aNewAccountIsAskedForWithNoHint() throws {
let request = SignInRequest(server: server, hint: "alice.bsky.social", create: true)
let asked = Form.decode(try #require(URLComponents(url: request.url, resolvingAgainstBaseURL: false)?.percentEncodedQuery))
#expect(asked["prompt"] == "create")
#expect(asked["login_hint"] == nil)
#expect(asked["client_id"] == "https://hud.example/oauth/app-client.json")
let plain = Form.decode(try #require(URLComponents(url: SignInRequest(server: server).url, resolvingAgainstBaseURL: false)?.percentEncodedQuery))
#expect(plain["prompt"] == nil)
}
@Test func theTypeaheadIsAskedFromTwoLettersWithoutTheAt() {
#expect(FoundActor.query(" @al ") == "al")
#expect(FoundActor.query("@a") == nil)
#expect(FoundActor.query("a") == nil)
#expect(FoundActor.query("alice.bsky.social") == "alice.bsky.social")
}
@Test func aMatchNeedsADIDAndAHandleAndItsAvatarHTTPS() {
let found = FoundActor(["did": "did:plc:a", "handle": "alice.test", "displayName": "Alice", "avatar": "https://cdn.example/a.jpg"])
#expect(found?.handle == "alice.test")
#expect(found?.displayName == "Alice")
#expect(found?.avatar == URL(string: "https://cdn.example/a.jpg"))
#expect(FoundActor(["did": "did:plc:a", "handle": "alice.test", "avatar": "http://cdn.example/a.jpg"])?.avatar == nil)
#expect(FoundActor(["did": "did:plc:a", "handle": "handle.invalid"]) == nil)
#expect(FoundActor(["did": "alice", "handle": "alice.test"]) == nil)
#expect(FoundActor(["handle": "alice.test"]) == nil)
}
@Test func aRefreshThatLeavesOutTheRefreshTokenKeepsTheOld() throws {
let old = Tokens(access: "a0", refresh: "r0", expires: .distantPast, did: "did:plc:a")
let now = Date(timeIntervalSince1970: 1000)
let renewed = try Tokens(["access_token": "a1", "token_type": "Bearer", "expires_in": 3600], previous: old, now: now)
#expect(renewed.access == "a1")
#expect(renewed.refresh == "r0")
#expect(renewed.did == "did:plc:a")
#expect(renewed.expires == now.addingTimeInterval(3600))
#expect(throws: SignInError.self) { try Tokens(["access_token": "a1", "token_type": "DPoP"], previous: old) }
}
}
@Suite struct KeptAccountsOfAServer {
let server = AuthServer(
issuer: "https://hud.example",
authorizationEndpoint: URL(string: "https://hud.example/oauth/authorize")!,
tokenEndpoint: URL(string: "https://hud.example/oauth/token")!,
revocationEndpoint: nil
)
private func entry(_ did: String, _ access: String, handle: String? = nil) -> KeptAccounts.Entry {
KeptAccounts.Entry(server: server, tokens: Tokens(access: access, refresh: "r-\(access)", expires: .distantFuture, did: did), did: did, handle: handle)
}
@Test func oneSignedInIsInUseAndTheOthersKeptTheOneUsedLastFirst() {
var kept = KeptAccounts()
kept.keep(entry("did:plc:a", "a1", handle: "alice.test"))
kept.keep(entry("did:plc:b", "b1"))
kept.keep(entry("did:plc:c", "c1"))
#expect(kept.current?.did == "did:plc:c")
#expect(kept.listed.map(\.did) == ["did:plc:c", "did:plc:b", "did:plc:a"])
#expect(kept.listed.last?.handle == "alice.test")
}
@Test func switchingPutsTheAccountInUseAndKeepsTheRest() {
var kept = KeptAccounts()
kept.keep(entry("did:plc:a", "a1"))
kept.keep(entry("did:plc:b", "b1"))
let switched = kept.use("did:plc:a")
#expect(switched)
#expect(kept.listed.map(\.did) == ["did:plc:a", "did:plc:b"])
let unknown = kept.use("did:plc:z")
#expect(!unknown)
#expect(kept.listed.map(\.did) == ["did:plc:a", "did:plc:b"])
}
@Test func anAccountsEntryIsFoundWithoutPuttingItInUse() {
var kept = KeptAccounts()
kept.keep(entry("did:plc:a", "a1"))
kept.keep(entry("did:plc:b", "b1"))
#expect(kept.entry("did:plc:a")?.tokens.access == "a1")
#expect(kept.entry(nil)?.did == "did:plc:b")
#expect(kept.entry("did:plc:z") == nil)
#expect(kept.listed.map(\.did) == ["did:plc:b", "did:plc:a"])
}
@Test func signingInAgainReplacesTheAccountKeepingItsHandle() {
var kept = KeptAccounts()
kept.keep(entry("did:plc:a", "a1", handle: "alice.test"))
kept.keep(entry("did:plc:b", "b1"))
let replaced = kept.keep(entry("did:plc:a", "a2"))
#expect(replaced?.tokens.access == "a1")
#expect(kept.listed == [KeptAccount(did: "did:plc:a", handle: "alice.test"), KeptAccount(did: "did:plc:b", handle: nil)])
#expect(kept.current?.tokens.access == "a2")
}
@Test func oneEndedGoesAndTheNextIsInUseUnlessSignedInToAfresh() {
var kept = KeptAccounts()
let first = entry("did:plc:a", "a1")
kept.keep(first)
kept.keep(entry("did:plc:b", "b1"))
kept.keep(entry("did:plc:c", "c1"))
kept.remove("did:plc:c", holding: entry("did:plc:c", "c1").tokens)
#expect(kept.current?.did == "did:plc:b")
// A session ended after its account was signed in to again leaves the new one.
kept.keep(entry("did:plc:a", "a2"))
kept.remove("did:plc:a", holding: first.tokens)
#expect(kept.listed.map(\.did) == ["did:plc:a", "did:plc:b"])
kept.remove("did:plc:a", holding: entry("did:plc:a", "a2").tokens)
kept.remove("did:plc:b", holding: entry("did:plc:b", "b1").tokens)
#expect(kept.current == nil)
}
@Test func renewedTokensAreKeptOnlyInPlaceOfThoseRenewed() {
var kept = KeptAccounts()
let old = entry("did:plc:a", "a1").tokens
kept.keep(entry("did:plc:a", "a1"))
kept.renew("did:plc:a", from: old, to: entry("did:plc:a", "a2").tokens)
#expect(kept.current?.tokens.access == "a2")
kept.renew("did:plc:a", from: old, to: entry("did:plc:a", "a3").tokens)
#expect(kept.current?.tokens.access == "a2")
kept.name("did:plc:a", "alice.test")
#expect(kept.listed.first?.handle == "alice.test")
}
@Test func theyAreReadAsWrittenAndTheOneSessionKeptBeforeAsTheirs() throws {
var kept = KeptAccounts()
kept.keep(entry("did:plc:a", "a1", handle: "alice.test"))
kept.keep(entry("did:plc:b", "b1"))
#expect(KeptAccounts.decode(try JSONEncoder().encode(kept)) == kept)
struct Single: Codable {
var server: AuthServer
var tokens: Tokens
}
let before = try JSONEncoder().encode(Single(server: server, tokens: entry("did:plc:a", "a1").tokens))
#expect(KeptAccounts.decode(before).listed == [KeptAccount(did: "did:plc:a", handle: nil)])
#expect(KeptAccounts.decode(Data("nonsense".utf8)).current == nil)
#expect(KeptAccounts.decode(nil).current == nil)
}
}