~ 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
193 lines · 7.6 KB Raw History
// What a launcher offers, read once for the page and shared by every
// launcher and the palette: who is signed in (from `describe_repo`), the
// apps they use (its `apps`, the most collections first), what HUD shows
// of their repository ("On atproto", the collections a bundled view
// draws), their feeds (Following, then those they saved), and the queries
// bundled views offer, by app (`apps`, from getWorkspace). Collections
// themselves are never listed.

import { accountOf, read, text, type Account } from '@hud/shared/result';
import type { IconName } from './icons';
import type { Actor } from './model';
import { appDomain, iconOf, type Names } from './tiles';
import { callTool } from './tools';
import type { Opening } from './workspace.svelte';
import type * as HudDefs from './lexicons/place/hud/defs.defs.ts';

/** One row: where it goes in the launcher, how it shows, what search finds it by, and what it opens. */
export type Row = {
	key: string;
	/** `mine`: an app the account uses, opening its page. */
	section: 'mine' | 'views' | 'feeds' | 'apps';
	/** For an app's query, the app. */
	group: string | null;
	text: string;
	sub: string | null;
	icon: IconName | null;
	/** Its app's domain, whose favicon stands before `icon`. */
	domain: string | null;
	/** A feed's picture, or null for its initial; undefined for an icon. */
	picture?: string | null;
	tag: { text: string; kind: 'count' } | null;
	find: string;
	call: Opening;
};

/** An app the account uses, as `describe_repo` answers it (`apps`): its domain and its name. */
export type App = { domain: string; name: string };

const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error));
const isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);

type Feed = { uri: string; name: string; avatar: string | null };

/** The apps a `describe_repo` result names, in its order (the most collections first). */
function appsOf(data: unknown): App[] {
	const apps = isObject(data) && Array.isArray(data.apps) ? data.apps : [];
	return apps.flatMap((app): App[] =>
		isObject(app) && typeof app.domain === 'string' && typeof app.name === 'string' ? [{ domain: app.domain, name: app.name }] : []
	);
}

class LauncherData {
	me = $state<Actor>({ did: '' });
	repo = $state<Account | null>(null);
	/** The apps the account uses, from `describe_repo`'s `apps`, the most collections first. */
	mine = $state.raw<App[]>([]);
	repoError = $state<string | null>(null);
	feeds = $state<Feed[] | null>(null);
	feedsError = $state<string | null>(null);
	/** The queries bundled views offer, as getWorkspace gives them. */
	apps = $state.raw<HudDefs.Launcher[]>([]);

	/** The account's name and picture, from its profile record. */
	readonly account = $derived.by(() => {
		const value = this.repo?.profile?.value;
		const profile = isObject(value) ? value : {};
		return {
			name: typeof profile.displayName === 'string' && profile.displayName.trim() ? profile.displayName : (this.me.handle ?? this.me.did),
			avatar: isObject(profile.avatar) && typeof profile.avatar.url === 'string' ? profile.avatar.url : null
		};
	});

	/** Each collection a bundled view draws, by its NSID: the view's description. */
	readonly #viewed = $derived(new Map((this.repo?.views ?? []).map((view) => [view.collection, view.description])));

	/** The names the rows give, for a tile's title: a collection's, a saved feed's by its at-uri, and an app's by its domain. */
	readonly names: Names = {
		collection: (nsid) => this.#viewed.get(nsid),
		feed: (uri) => this.feeds?.find((feed) => feed.uri === uri)?.name,
		app: (domain) => this.mine.find((app) => app.domain === domain)?.name ?? this.apps.find((app) => app.domain === domain)?.app
	};

	readonly rows = $derived.by((): Row[] => {
		const did = this.me.did;
		const viewed = this.#viewed;
		// A collection no view draws has no name to give: its tile says what it is.
		const collection = (collection: string): Opening => ({ tool: 'list_records', arguments: { actor: did, collection }, title: viewed.get(collection) });
		const views: Row[] = (this.repo?.views ?? []).map((view) => ({
			key: `view:${view.collection}`,
			section: 'views',
			group: null,
			text: view.description,
			sub: null,
			icon: iconOf('list_records', { collection: view.collection }),
			domain: appDomain(view.collection),
			tag: null,
			find: view.description.toLowerCase(),
			call: collection(view.collection)
		}));
		const timeline: Opening = { tool: 'query', arguments: { method: 'app.bsky.feed.getTimeline', params: {} }, title: 'Following' };
		const feeds: Row[] = [
			{ key: 'feed:following', section: 'feeds', group: null, text: 'Following', sub: null, icon: 'feed', domain: 'bsky.app', tag: null, find: 'following feed', call: timeline },
			...(this.feeds ?? []).map(
				(feed): Row => ({
					key: `feed:${feed.uri}`,
					section: 'feeds',
					group: null,
					text: feed.name,
					sub: null,
					icon: null,
					domain: null,
					picture: feed.avatar,
					tag: null,
					find: `${feed.name} feed`.toLowerCase(),
					call: { tool: 'query', arguments: { method: 'app.bsky.feed.getFeed', params: { feed: feed.uri } }, title: feed.name }
				})
			)
		];
		const apps: Row[] = this.apps.map((app) => ({
			key: `app:${app.method}:${app.title}`,
			section: 'apps',
			group: app.app,
			text: app.title,
			sub: null,
			icon: iconOf('query', { method: app.method }),
			domain: app.domain,
			tag: null,
			find: `${app.title} ${app.app}`.toLowerCase(),
			call: { tool: 'query', arguments: { method: app.method, params: isObject(app.params) ? app.params : {}, service: app.service }, title: app.title }
		}));
		const mine: Row[] = this.mine.map((app) => ({
			key: `mine:${app.domain}`,
			section: 'mine',
			group: null,
			text: app.name,
			sub: app.domain,
			icon: 'app',
			domain: app.domain,
			tag: null,
			find: `${app.name} ${app.domain} app`.toLowerCase(),
			call: { tool: 'describe_app', arguments: { domain: app.domain, actor: 'me' }, title: app.name }
		}));
		return [...mine, ...views, ...feeds, ...apps];
	});

	#started = false;

	/** Read it, the first time a launcher or the palette shows. */
	start(me: Actor) {
		this.me = me;
		if (this.#started) return;
		this.#started = true;
		void this.loadRepo();
		void this.loadFeeds();
	}

	async loadRepo() {
		this.repoError = null;
		try {
			const result = await callTool('describe_repo', { actor: this.me.did });
			const view = read(result);
			const account = accountOf(view);
			if (account) {
				this.repo = account;
				this.mine = appsOf(result.structuredContent);
			} else this.repoError = view.renderer === 'error' ? view.message : 'HUD could not describe your repository.';
		} catch (error) {
			this.repoError = errorText(error);
		}
	}

	async loadFeeds() {
		this.feedsError = null;
		try {
			const result = await callTool('query', { method: 'app.bsky.feed.getFeedGenerators', params: { feeds: 'saved' } });
			if (result.isError) {
				this.feedsError = text(result) || 'Your saved feeds could not be read.';
				return;
			}
			const data = result.structuredContent;
			const response = isObject(data) && isObject(data.response) ? data.response : {};
			this.feeds = (Array.isArray(response.feeds) ? response.feeds : []).flatMap((feed): Feed[] =>
				isObject(feed) && typeof feed.uri === 'string'
					? [{ uri: feed.uri, name: typeof feed.displayName === 'string' && feed.displayName ? feed.displayName : feed.uri, avatar: typeof feed.avatar === 'string' ? feed.avatar : null }]
					: []
			);
		} catch (error) {
			this.feedsError = errorText(error);
		}
	}
}

export const launcher = new LauncherData();