~ 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
202 lines · 13.0 KB Raw History
// The gallery's made-up answers: what the views only a signed-in account
// sees (its timeline, its chats, its notifications) would answer
// `me`, as the query tool answers one, `_meta.viewer` naming `me` so that
// `hud resolve` draws them as theirs (their own messages theirs, a chat's
// box to send). Made of the real people and posts record.mjs recorded, so
// the faces and pictures are real; every answer, and each join in it, is
// held to its method's lexicon by `check`.

/** A query tool's answer, as the server gives it to the signed-in `me`. */
const answer = (me, method, service, params, response, summary, joins) => ({
	content: [{ type: 'text', text: summary }],
	structuredContent: { method, service, params, response, ...(joins ? { joins } : {}) },
	isError: false,
	_meta: { viewer: { did: me.did, handle: me.handle } }
});

const BSKY = 'did:web:api.bsky.app#bsky_appview';
const CHAT = 'did:web:api.bsky.chat#bsky_chat';
const KNOTLESS = 'did:web:knotless.dev#knotless_appview';
const GRAIN = 'did:web:grain.social#grain_appview';

/** Minutes before the gallery's moment, as a datetime. */
const ago = (minutes) => new Date(Date.parse('2026-11-16T23:30:00.000Z') - minutes * 60_000).toISOString();

/**
 * The made-up answers, by entry id. `people` are the profiles recorded
 * (getProfiles), by handle; `recorded` the recorded answers, by entry id;
 * `me` the gallery's account. `entries` give each its call's arguments.
 */
export function made({ me, people, recorded, args }) {
	const who = (handle) => people[handle] ?? fail(`no profile recorded for ${handle}`);
	const basic = (handle) => {
		const p = who(handle);
		return { did: p.did, handle: p.handle, ...(p.displayName ? { displayName: p.displayName } : {}), ...(p.avatar ? { avatar: p.avatar } : {}) };
	};
	const dan = basic('danabra.mov');
	const paul = basic('pfrazee.com');
	const bryan = basic('bnewbold.net');
	const jay = basic('jay.bsky.team');
	const self = basic(me.handle);

	// Messages, newest first, as the chat service answers them.
	let n = 0;
	const message = (from, minutes, text, extra = {}) => ({
		$type: 'chat.bsky.convo.defs#messageView',
		id: `3n2msg${String(++n).padStart(7, '0')}`,
		rev: `22222${String(n).padStart(8, '0')}`,
		text,
		sender: { did: from.did },
		sentAt: ago(minutes),
		...extra
	});
	const reaction = (from, value, minutes) => ({ value, sender: { did: from.did }, createdAt: ago(minutes) });

	const withDan = [
		message(dan, 4, 'see you thursday then. bring the lexicon questions'),
		message(self, 6, 'Perfect. I’ll put the gallery up on the big screen so we can go tile by tile.', { reactions: [reaction(dan, '👍', 5)] }),
		message(dan, 9, 'thursday works for me. same room as last time?'),
		message(self, 12, 'Want to go over the HUD gallery before the reading group? Thursday after lunch?'),
		{ $type: 'chat.bsky.convo.defs#deletedMessageView', id: 'n2msgdeleted0', rev: '2222200000000', sender: { did: dan.did }, sentAt: ago(14) }
	];
	const direct = (id, other, last, unread, extra = {}) => ({
		id,
		rev: `33333${id.length}`,
		members: [self, other],
		lastMessage: last,
		muted: false,
		unreadCount: unread,
		status: 'accepted',
		kind: { $type: 'chat.bsky.convo.defs#directConvo' },
		...extra
	});
	const danConvo = direct('3n2dan0chat', dan, withDan[0], 1);

	const group = [
		message(bryan, 3, 'I can take the sync section. The firehose part has changed a lot since the last time we read it.'),
		message(paul, 8, 'Agenda for Thursday: permissions, then lexicon publishing. Dan’s two posts as the reading.', { reactions: [reaction(self, '🙌', 7), reaction(bryan, '👍', 6)] }),
		message(self, 15, 'Added the two posts to our canvas so everyone has them open.'),
		{
			$type: 'chat.bsky.convo.defs#systemMessageView',
			id: '3n2msgsystem1',
			rev: '2222200000001',
			sentAt: ago(20),
			data: { $type: 'chat.bsky.convo.defs#systemMessageDataMemberJoin', member: { did: bryan.did }, role: 'standard', approvedBy: { did: paul.did } }
		},
		message(dan, 30, 'welcome everyone 👋')
	];
	const groupConvo = {
		id: args['bsky-chat'].params.convoId,
		rev: '3333300000002',
		members: [self, dan, paul, bryan],
		lastMessage: group[0],
		muted: false,
		unreadCount: 2,
		status: 'accepted',
		kind: { $type: 'chat.bsky.convo.defs#groupConvo', name: 'Atproto reading group', createdAt: ago(60 * 24 * 9), lockStatus: 'unlocked', lockStatusModerationOverride: false, memberCount: 4, memberLimit: 50 }
	};
	const paulConvo = direct('3n2paul0chat', paul, message(self, 60 * 5, 'Thanks for the review on the canvas lexicons!'), 0);
	const jayConvo = direct('3n2jay0chat', jay, message(jay, 60 * 26, 'Hi! Saw your post about HUD, would love a demo sometime.'), 1, { status: 'request' });

	// The timeline: the recorded Discover and Dan's posts, in turn, one of them liked by `me`.
	const discover = recorded['bsky-feed'].structuredContent.response.feed;
	const dans = recorded['bsky-author-feed'].structuredContent.response.feed;
	const feed = [];
	for (let i = 0; feed.length < 6 && (i < discover.length || i < dans.length); i++) {
		if (dans[i]) feed.push(structuredClone(dans[i]));
		if (discover[i] && feed.length < 6) feed.push(structuredClone(discover[i]));
	}
	const liked = feed.find((item) => !item.reason);
	liked.post.viewer = { ...liked.post.viewer, like: `at://${me.did}/app.bsky.feed.like/3n2gallery0lk` };
	liked.post.likeCount = (liked.post.likeCount ?? 0) + 1;

	// knotless notifications, of the real repository and pull the gallery shows.
	const repo = { did: me.did, handle: me.handle, name: 'knotless' };
	const pull = args['knotless-thread'].params.uri;
	const issues = recorded['knotless-items'].structuredContent.response.items;
	const issue = issues[0]?.uri ?? fail('no open issue recorded in knotless-items');
	const issueTitle = issues[0].title;
	const pullTitle = recorded['knotless-thread'].structuredContent.response.item.title;
	const actor = (p) => ({ did: p.did, handle: p.handle, ...(p.avatar ? { avatar: p.avatar } : {}) });
	const reviewer = { did: 'did:plc:kqi2glvzerg4dt66k64co2sl', handle: 'review.knotless.dev', bot: true };
	const notification = (author, reason, minutes, extra) => ({ uri: `at://${author.did}/dev.knotless.comment/3n2note${String(minutes).padStart(5, '0')}`, author, reason, isRead: minutes > 60, createdAt: ago(minutes), repo, ...extra });
	const notifications = [
		notification(reviewer, 'review-requested', 2, { title: pullTitle, reasonSubject: pull, subjectState: 'open' }),
		notification(actor(dan), 'comment', 11, { title: issueTitle, reasonSubject: issue, subjectState: 'open', text: 'I can reproduce this on a cold cache too; it only shows when two writers race.' }),
		notification(reviewer, 'comment', 25, { title: pullTitle, reasonSubject: pull, subjectState: 'merged', verdict: 'approve', reviewed: true, lineComments: 2 }),
		notification(actor(paul), 'mention', 70, { title: issueTitle, reasonSubject: issue, subjectState: 'open', mentioned: true, text: '@chadtmiller.com this looks like the eviction order we talked about.' }),
		notification(actor(bryan), 'star', 60 * 5, { uri: `at://${bryan.did}/dev.knotless.star/3n2star000001`, reasonSubject: `at://${me.did}/dev.knotless.repo/knotless` }),
		{ ...notification(actor(self), 'checks-failed', 60 * 8, { title: pullTitle, reasonSubject: pull, subjectState: 'open', checks: [{ workflow: 'test', status: 'failure' }, { workflow: 'e2e', status: 'error' }] }), uri: pull },
		notification(actor(jay), 'follow', 60 * 30, { uri: `at://${jay.did}/dev.knotless.follow/3n2follow0001` })
	];

	// Bluesky notifications about a post of `me`'s, the post as the join fetches it.
	const post = recorded['bsky-author-feed'].structuredContent.response.feed[0].post;
	const mine = { uri: `at://${me.did}/app.bsky.feed.post/3n2mypost0001`, cid: post.cid };
	const myPost = { $type: 'app.bsky.feed.post', text: 'HUD draws any atproto app as tiles on a canvas. Next up: notifications, Bluesky’s and Grain’s, each in its own tile.', createdAt: ago(60 * 2) };
	const bsky = (author, reason, minutes, record, extra = {}) => ({ uri: `at://${author.did}/${record.$type}/3n2bsky${String(minutes).padStart(6, '0')}`, cid: post.cid, author, reason, record, isRead: minutes > 60, indexedAt: ago(minutes), ...extra });
	const reply = { root: mine, parent: mine };
	const zz = basic('zzstoatzz.io');
	const bskyNotifications = [
		bsky(dan, 'like', 3, { $type: 'app.bsky.feed.like', subject: mine, createdAt: ago(3) }, { reasonSubject: mine.uri }),
		bsky(paul, 'reply', 12, { $type: 'app.bsky.feed.post', text: 'Nice. Does a page more fetch the older posts too?', reply, createdAt: ago(12) }, { reasonSubject: mine.uri }),
		bsky(bryan, 'repost', 40, { $type: 'app.bsky.feed.repost', subject: mine, createdAt: ago(40) }, { reasonSubject: mine.uri }),
		bsky(jay, 'quote', 60 * 3, { $type: 'app.bsky.feed.post', text: 'This one is worth watching.', embed: { $type: 'app.bsky.embed.record', record: mine }, createdAt: ago(60 * 3) }, { reasonSubject: mine.uri }),
		bsky(zz, 'follow', 60 * 20, { $type: 'app.bsky.graph.follow', subject: me.did, createdAt: ago(60 * 20) })
	];
	const subjects = { posts: [{ uri: mine.uri, cid: mine.cid, author: self, record: myPost, likeCount: 1, repostCount: 1, replyCount: 1, quoteCount: 1, indexedAt: myPost.createdAt }] };

	// Grain notifications, on the recorded galleries, by their photographers.
	const galleries = recorded['grain-feed'].structuredContent.response.items;
	const creator = (i) => {
		const c = galleries[i].creator;
		return { did: c.did, handle: c.handle, ...(c.displayName ? { displayName: c.displayName } : {}), ...(c.avatar ? { avatar: c.avatar } : {}) };
	};
	const on = (i) => ({ galleryUri: galleries[i].uri, galleryTitle: galleries[i].title, galleryThumb: galleries[i].items[0].thumb });
	const grain = (author, reason, minutes, collection, extra = {}) => ({ uri: `at://${author.did}/${collection}/3n2grain${String(minutes).padStart(5, '0')}`, reason, createdAt: ago(minutes), indexedAt: ago(minutes), isRead: minutes > 60, author, ...extra });
	const grainNotifications = [
		grain(creator(2), 'gallery-favorite', 4, 'social.grain.favorite', on(0)),
		grain(creator(1), 'gallery-comment', 18, 'social.grain.comment', { ...on(3), commentText: 'That light through the fog is unreal.' }),
		grain(creator(0), 'reply', 60 * 2, 'social.grain.comment', { ...on(0), replyToText: 'Which lens was this?', commentText: 'The 35mm, wide open.' }),
		grain(creator(2), 'follow', 60 * 9, 'social.grain.graph.follow')
	];

	const a = (id, method, service, response, summary, joins) => [id, answer(me, method, service, args[id].params, response, summary, joins)];
	return Object.fromEntries([
		a('bsky-timeline', 'app.bsky.feed.getTimeline', BSKY, { feed, cursor: feed.at(-1).post.indexedAt }, `${feed.length} posts from app.bsky.feed.getTimeline on api.bsky.app`),
		a('bsky-chats', 'chat.bsky.convo.listConvos', CHAT, { convos: [danConvo, groupConvo, paulConvo, jayConvo] }, '4 chats from chat.bsky.convo.listConvos on api.bsky.chat: Atproto reading group'),
		a('bsky-chat', 'chat.bsky.convo.getMessages', CHAT, { messages: group, relatedProfiles: [self, dan, paul, bryan] }, `${group.length} messages from chat.bsky.convo.getMessages on api.bsky.chat`),
		a('bsky-chat-with', 'chat.bsky.convo.getConvoForMembers', CHAT, { convo: danConvo }, `Chat with ${dan.handle}: ${withDan.length} messages.`, { messages: { messages: withDan } }),
		a('bsky-chat-availability', 'chat.bsky.convo.getConvoAvailability', CHAT, { canChat: true, convo: danConvo }, `You can message ${dan.handle}.`),
		a('knotless-notifications', 'dev.knotless.listNotifications', KNOTLESS, { notifications, seenAt: ago(60) }, `${notifications.length} notifications from dev.knotless.listNotifications on knotless.dev`),
		a('bsky-notifications', 'app.bsky.notification.listNotifications', BSKY, { notifications: bskyNotifications, seenAt: ago(60) }, `${bskyNotifications.length} notifications from app.bsky.notification.listNotifications on api.bsky.app`, { subjects }),
		a('grain-notifications', 'social.grain.notification.listNotifications', GRAIN, { notifications: grainNotifications, seenAt: ago(60) }, `${grainNotifications.length} notifications from social.grain.notification.listNotifications on grain.social`)
	]);
}

/** The joins a made-up answer holds, by its method: the method each join's answer is of. */
const JOINS = {
	'chat.bsky.convo.getConvoForMembers': { messages: 'chat.bsky.convo.getMessages' },
	'app.bsky.notification.listNotifications': { subjects: 'app.bsky.feed.getPosts' }
};

/** Every made-up answer held to its method's lexicon, and each join to its own: the problems, none when all are valid. */
export function check(lexicons, answers) {
	const problems = [];
	for (const [id, { structuredContent: s }] of Object.entries(answers)) {
		const hold = (method, value, what) => {
			try {
				lexicons.assertValidXrpcOutput(method, value);
			} catch (e) {
				problems.push(`${id}: ${what} is not as ${method} says: ${e.message}`);
			}
		};
		hold(s.method, s.response, 'the answer');
		for (const [as, method] of Object.entries(JOINS[s.method] ?? {})) hold(method, s.joins?.[as], `its join ${as}`);
	}
	return problems;
}

function fail(why) {
	throw new Error(why);
}