~ 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
214 lines · 11.0 KB Raw History
// What an app's server reads for a page before it is drawn (`@hud/shell/
// server`): the screen a URL is (`screenAt`), what every page knows of the
// account (`frameData`: its tabs' badges, its picture, its scheme, the
// browser's accounts), and the app's look for the page's head
// (`lookHead`). It calls HUD as the request's account through the host's
// `Caller`, which holds its session: a `Hud` of the server's `Sessions`
// (session.ts), which keeps the browser's accounts and answers the shell's
// endpoints.

import { read, viewer, type Call, type ToolResult } from '@hud/shared/result';
import { at, isTabPath, measureOf, rootsOf, routesOf, swappedTab, tabPath, type App, type Measure } from './app';
import { backPath } from './back';
import { SignInNeeded } from './client';
import { callOf, Names, same, type Found } from './routes';
import { carried, type Answer, type Screen } from './screen';
import { lookCss, schemeIn } from './theme';
import type { AccountsData, Hud } from './session';

export { Hud, Sessions, type AccountRow, type AccountsData, type Cookies, type SessionsConfig } from './session';
export type { Session } from './oauth';

/** HUD's tools as the server calls them for a request, as its account where it has one: a result, failures included (`isError`), or `SignInNeeded` thrown where it needs an account; and a handle's DID (the handle as it is where it cannot be resolved). */
export type Caller = {
	call(name: string, args: Record<string, unknown>): Promise<ToolResult>;
	resolve(actor: string): Promise<string>;
};

/** A call answered for a page: its result as the page carries it, its accounts learnt. */
async function answer(hud: Caller, call: Call, names: Names): Promise<Answer> {
	try {
		const result = await hud.call(call.name, call.args);
		names.learn(result.structuredContent);
		const who = result.isError ? null : viewer(result);
		if (who) names.viewer(who);
		return { result: carried(result) };
	} catch (error) {
		if (error instanceof SignInNeeded) return { signIn: true };
		return { failed: error instanceof Error ? error.message : String(error) };
	}
}

/**
 * The page at a URL, as the app's routes say (routes.ts), answered by HUD
 * for the page to draw: a tab's root at the tab's own URL, each tab's root
 * chosen for this page (`rootsOf`: signed in, Grain's Home the first feed
 * the person pinned); a route's screen that is a tab's root as that tab,
 * or that is by the account its answer names (the account's own profile,
 * the Profile tab's `me`), or that its tree's strip offers in a tab's
 * root's place (`swappedTab`: Following, a pinned feed) as that tab's
 * root level, its strip shown, drawn as wide as the tab's own root is
 * (its call answered after the screen's, for its measure alone); any
 * other over the root of the tab its route names (the first, where it
 * names none). As the app in the browser draws a URL it has no history
 * of. With it, what the root under it answers (streamed), and its status
 * (404 where no route has its path, 502 where HUD could not answer).
 */
export async function screenAt(app: App, url: URL, hud: Caller, signedIn: boolean): Promise<{ screen: Screen; under: Promise<Answer> | null; status: number }> {
	const names = new Names();
	const resolve = (actor: string) => hud.resolve(actor);
	// Read beside the URL's route: the tabs' roots are the account's to choose.
	const rooting = rootsOf(app, signedIn, (call) => queried(hud, call), resolve);
	let tab = app.tabs.findIndex((t) => isTabPath(tabPath(app, t, names), url.pathname, url.search));
	let screen: Call | null = null;
	if (tab < 0) {
		const found = await callOf(url.pathname, url.search, routesOf(app), resolve);
		if (!found) return { screen: { tab: 0, calls: [], top: null, names: [], missing: true }, under: null, status: 404 };
		if (found.pager) return storyAt(app, found, hud, names, rooting, resolve);
		const roots = await rooting;
		tab = roots.findIndex((own) => own !== null && same(own, found.call));
		if (tab < 0) [tab, screen] = [Math.max(0, app.tabs.findIndex((t) => t.label === found.tab)), found.call];
	}
	const roots = await rooting;
	const root = roots[tab];
	let calls = [...(root ? [root] : []), ...(screen ? [screen] : [])];
	const last = calls.at(-1);
	const aside = app.frame?.aside?.call;
	const [top, beside] = await Promise.all([last ? answer(hud, last, names) : null, aside ? answer(hud, aside, names) : null]);
	// A screen that is a tab's own, by the account its answer named (`/profile/<own handle>`, the Profile tab's `me`): that tab, at its root, drawn from the same answer.
	const own = screen ? app.tabs.findIndex((t) => tabPath(app, t, names) === url.pathname) : -1;
	const ownRoot = own >= 0 ? roots[own] : null;
	let measure: Measure | undefined;
	if (ownRoot) [tab, calls] = [own, [ownRoot]];
	else if (screen && top && 'result' in top) {
		const view = read(top.result);
		const swapped = view.renderer === 'tree' ? swappedTab(roots, view.ui) : -1;
		if (swapped >= 0) {
			[tab, calls] = [swapped, [screen]];
			// In a tab's root's place, as wide as that root: a strip's choice never changes the screen's width.
			const rooted = await answer(hud, roots[swapped] as Call, new Names());
			const drawn = 'result' in rooted ? read(rooted.result) : null;
			measure = drawn?.renderer === 'tree' ? measureOf(drawn.ui) : 'content';
		}
	}
	// The root under a screen does not show: it streams after the page.
	const under = calls.length > 1 ? answer(hud, calls[0], new Names()) : null;
	const status = top && 'failed' in top ? 502 : 200;
	return { screen: { tab, calls, top, aside: beside, names: names.entries(), missing: false, roots, ...(measure ? { measure } : {}) }, under, status };
}

/**
 * A story's URL (a route's with `pager`): the story viewer, its one page
 * the story's screen answered for the page (so its HTML and head are the
 * story's), over the screen its route's `under` names (its account's
 * profile; one that is a tab's own, as one's own profile, that tab at its
 * root), over that screen's tab's root, so closing the story goes there.
 * The root streams after the page; the screen between, which does not
 * show, the browser reads.
 */
async function storyAt(
	app: App,
	found: Found,
	hud: Caller,
	names: Names,
	rooting: Promise<(Call | null)[]>,
	resolve: (actor: string) => Promise<string>
): Promise<{ screen: Screen; under: Promise<Answer> | null; status: number }> {
	const aside = app.frame?.aside?.call;
	const [top, below, roots, beside] = await Promise.all([
		answer(hud, found.call, names),
		found.under ? callOf(found.under, '', routesOf(app), resolve) : null,
		rooting,
		aside ? answer(hud, aside, names) : null
	]);
	const own = found.under ? app.tabs.findIndex((t) => tabPath(app, t, names) === found.under) : -1;
	const tab = own >= 0 ? own : Math.max(0, app.tabs.findIndex((t) => t.label === (below?.tab ?? found.tab)));
	const root = roots[tab];
	const calls = [...(root ? [root] : []), ...(own < 0 && below ? [below.call] : [])];
	const under = root ? answer(hud, root, new Names()) : null;
	const status = 'failed' in top ? 502 : 200;
	const pager = { calls: [found.call], at: 0 };
	return { screen: { tab, calls, top, aside: beside, names: names.entries(), missing: false, roots, pager }, under, status };
}

/**
 * The app's own sign-in screen, at the host's sign-in path `url`: drawn in
 * the frame over no tab, coming back to its `back` (a path of this origin,
 * else home), the `handle` and `error` it holds those it was sent back with
 * (`Hud.callback`'s), or those of its form's post the host answered
 * (`failed`, `Hud.signIn`'s).
 */
export function signInScreen(url: URL, failed?: { handle: string; error: string } | null): Screen {
	const q = url.searchParams;
	const signIn = { back: backPath(q.get('back'), url.origin), handle: failed?.handle ?? q.get('handle') ?? '', error: failed?.error ?? q.get('error') };
	return { tab: -1, calls: [], top: null, names: [], missing: false, signIn };
}

/** What a query answers, where it does, else null. */
async function queried(hud: Caller, call: Call): Promise<unknown> {
	const result = await hud.call(call.name, call.args).catch(() => null);
	return result && !result.isError ? result.structuredContent : null;
}

/**
 * What every page knows of the account, signed in: each tab's badge count
 * by its place, streamed after the page; the account's picture, read for
 * the page, so the frame draws it from the first paint (a host's loads run
 * beside the page's, which waits on its own screen anyway); its own scheme,
 * read where `scheme` asks (the host keeps it, so it is read once); and,
 * where the caller keeps the browser's accounts (a `Hud`), their rows, the
 * one in use's from the same answer as its picture.
 */
export async function frameData(
	app: App,
	hud: Caller & Partial<Pick<Hud, 'accounts'>>,
	signedIn: boolean,
	scheme: boolean
): Promise<{ counts: Promise<Record<number, number>> | null; picture: string | null; scheme: 'light' | 'dark' | null | undefined; accounts: AccountsData | null }> {
	if (!signedIn) return { counts: null, picture: null, scheme: undefined, accounts: null };
	const own = app.scheme;
	const shown = app.frame?.account?.picture;
	const profile = shown ? queried(hud, shown.call) : Promise.resolve(null);
	const [chosen, found, accounts] = await Promise.all([own && scheme ? queried(hud, own.call) : undefined, profile, hud.accounts ? hud.accounts(app, profile) : null]);
	const picture = shown ? pictureIn(found, shown.at) : null;
	const badges = app.tabs.flatMap((tab, i) => (tab.badge ? [{ i, badge: tab.badge }] : []));
	const counts =
		badges.length > 0
			? Promise.all(
					badges.map(async ({ i, badge }) => {
						const found = at(await queried(hud, badge.call), badge.count);
						return [i, typeof found === 'number' ? found : 0] as const;
					})
				).then((found) => Object.fromEntries(found) as Record<number, number>)
			: null;
	return { counts, picture, scheme: own && chosen ? schemeIn(chosen, own.at) : undefined, accounts };
}

/** The picture at a dotted path of an answer: an https URL, else none. */
export function pictureIn(answer: unknown, path: string): string | null {
	const found = at(answer, path);
	return typeof found === 'string' && found.startsWith('https://') ? found : null;
}

const attribute = (text: string) => text.replaceAll('&', '&amp;').replaceAll('"', '&quot;').replaceAll('<', '&lt;');

/**
 * The app's look, for the page's head as the server sends it: its palette
 * as the renderer's variables, and its fonts' stylesheet, loaded without
 * holding up the first paint (they swap in).
 */
export function lookHead(app: App): string {
	const look = app.look;
	if (!look) return '';
	const style = `<style>${lookCss(look)}</style>`;
	if (!look.fonts) return style;
	const href = attribute(look.fonts.href);
	const origin = new URL(look.fonts.href).origin;
	return [
		style,
		`<link rel="preconnect" href="${attribute(origin)}">`,
		'<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>',
		`<link rel="stylesheet" href="${href}" media="print" onload="this.media='all'">`,
		`<noscript><link rel="stylesheet" href="${href}"></noscript>`
	].join('');
}