~ 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
269 lines · 11.3 KB Raw History
// The playground's state: what it starts from (getPlayground: the bundled
// views, the catalog, HUD's themes), the work on it (a call, its tool and
// arguments, and a view, each as typed), and what the view drew of it.
//
// A view is drawn in two steps (place.hud.previewView): its call made once,
// afresh, what it answered (`structuredContent`) kept as the answer; then,
// while only layouts change, drawn again over that answer, nothing read
// again. What reads (the tool, its arguments, the view less its modes'
// layouts) is the answer's key: once it changes, the call is made afresh.
// An answer to a request older than the last is dropped.

import type { Answer as Answered } from '../xrpc';
import { procedure, xrpc, XrpcError } from '../xrpc';
import type * as getPlayground from '../lexicons/place/hud/getPlayground.defs.ts';
import type * as previewView from '../lexicons/place/hud/previewView.defs.ts';
import { read, text, viewer, type Call, type Entry, type ToolResult, type Viewer } from '@hud/shared/result';
import type { Theme } from '../theme';
import type { Catalog, Problem } from './editor';
import { BLANK, exampleOf, FIRST, isTool, type Example, type Tool } from './examples';
import { fromLink, keep, kept, linkOf } from './share';

/** A bundled view the playground starts from: its name (its file's), its document, the app it is of, and its call. */
export type Template = { name: string; view: Record<string, unknown>; app: string; example: Example };

/** What was read: the key it was read by, its answer, its summary (the tool's text), and who it was read as; or the tool's failure, for that key. */
export type Read = { key: string; data: unknown; summary: string; viewer: Viewer | null; at: string; failure: ToolResult | null };

/** What the preview says of what it shows: read afresh, or drawn over what was read, and when. */
export type Status = { how: 'read' | 'drawn'; at: string; read: string; viewer: Viewer | null };

/** A call a drawing opened, which the playground does not follow but says: and the template that draws it, if one does. */
export type Opened = { call: Call; tool: Tool | null; template: Template | null };

const MODES = ['list', 'record', 'query', 'page'];

const isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);

const pretty = (value: unknown) => JSON.stringify(value, null, 2);

/** `text` as JSON, or undefined where it is not. */
function parsed(text: string): unknown {
	try {
		return JSON.parse(text);
	} catch {
		return undefined;
	}
}

const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error));

export class Playground {
	/** Whether what it starts from was read, or why not. */
	phase: { kind: 'loading' } | { kind: 'ready' } | { kind: 'error'; message: string } = $state({ kind: 'loading' });
	templates: Template[] = $state.raw([]);
	catalog: Catalog | null = $state.raw(null);
	themes: Theme[] = $state.raw([]);

	tool: Tool = $state('query');
	/** The call's arguments, as typed: JSON, the view left out. */
	args = $state('{}');
	/** The view, as typed: a place.hud.view document. */
	view = $state('');
	/** The bundled view it began as, by name; none for a blank start or a link. */
	template: string | null = $state(null);
	/** The work as it began (a template, a link, a blank start): work that differs was edited. */
	baseline: string | null = $state(null);

	/** The server's problems with the view as last sent, none once it draws. */
	problems: Problem[] = $state.raw([]);
	/** What the preview draws: the last drawing, kept while the view has problems. */
	entry: Entry | null = $state.raw(null);
	/** The answer the view is drawn over, as read: never deeply reactive, as a feed's is large. */
	answer: Read | null = $state.raw(null);
	status: Status | null = $state.raw(null);
	busy = $state(false);
	opened: Opened | null = $state.raw(null);

	/** Counts requests, so an answer to an older one is dropped. */
	#generation = 0;

	/** The work, as one text, to tell whether it was edited. */
	work: string = $derived(JSON.stringify([this.tool, this.args, this.view]));

	edited: boolean = $derived(this.work !== this.baseline);

	/** The arguments as an object, or null while they are not one. */
	call: Record<string, unknown> | null = $derived.by(() => {
		const args = parsed(this.args);
		return isObject(args) ? args : null;
	});

	/** The view as an object, or null while it is not one. */
	document: Record<string, unknown> | null = $derived.by(() => {
		const view = parsed(this.view);
		return isObject(view) ? view : null;
	});

	/** Read what it starts from, and the work: from a link, else as the browser kept it, else the first template. */
	async load() {
		this.phase = { kind: 'loading' };
		const shared = await fromLink(location.hash);
		if (shared) {
			history.replaceState(null, '', location.pathname + location.search);
			this.#begin(shared.tool, shared.arguments, shared.view, null);
		} else {
			const found = kept();
			if (found) {
				this.tool = found.tool;
				this.args = found.args;
				this.view = found.view;
				this.template = found.template;
				this.baseline = found.baseline;
			}
		}
		try {
			const found: Answered<typeof getPlayground.main> = await xrpc<typeof getPlayground.main>('place.hud.getPlayground', {});
			// Each as a view given inline may be, app pages left out, by the server.
			this.templates = found.views.flatMap((bundled) => {
				const view = bundled.view;
				if (!isObject(view)) return [];
				return [{ name: bundled.name, view, app: bundled.app, example: exampleOf(bundled.name, view) }];
			});
			this.catalog = isObject(found.catalog) ? (found.catalog as Catalog) : null;
			this.themes = found.themes;
			this.phase = { kind: 'ready' };
		} catch (error) {
			this.phase = { kind: 'error', message: errorText(error) };
			return;
		}
		if (!shared && this.baseline === null) this.choose(FIRST);
	}

	/** Start from `view` and its call: the work as it begins. */
	#begin(tool: Tool, args: Record<string, unknown>, view: unknown, template: string | null) {
		const { view: _, ...rest } = args;
		this.tool = tool;
		this.args = pretty(rest);
		this.view = typeof view === 'string' ? view : pretty(view);
		this.template = template;
		this.baseline = this.work;
		this.problems = [];
		this.answer = null;
		this.entry = null;
		this.status = null;
		this.opened = null;
	}

	/** Start from a bundled view, by name, with its call. */
	choose(name: string) {
		const template = this.templates.find((t) => t.name === name) ?? this.templates[0];
		if (template) this.#begin(template.example.tool, template.example.arguments, template.view, template.name);
	}

	/** Start from a minimal view of one's own. */
	blank() {
		this.#begin(BLANK.example.tool, BLANK.example.arguments, BLANK.view, null);
	}

	/** Switch the tool: to a template's call for it, where it has one (a collection's record for get_record). */
	switchTool(tool: Tool) {
		const example = this.templates.find((t) => t.name === this.template)?.example;
		const args = example?.tool === tool ? example.arguments : tool === 'get_record' ? example?.record : undefined;
		this.tool = tool;
		if (args) this.args = pretty(args);
	}

	/** Keep the work for the next load. */
	keep() {
		keep({ tool: this.tool, args: this.args, view: this.view, template: this.template, baseline: this.baseline });
	}

	/** A link holding the call and the view, or null while either is not valid JSON. */
	async link(): Promise<string | null> {
		const args = this.call;
		const view = this.document;
		if (!args || !view) return null;
		const { view: _, ...rest } = args;
		const hash = await linkOf({ tool: this.tool, arguments: rest, view });
		return `${location.origin}${location.pathname}${hash}`;
	}

	/** The template that draws `call`, if a bundled view does: a query's method's, a collection's. */
	templateOf(call: Call): Template | null {
		const params = call.args;
		const collection = call.name === 'list_records' ? params.collection : call.name === 'get_record' && typeof params.uri === 'string' ? params.uri.split('/')[3] : null;
		return (
			this.templates.find(({ view }) => {
				if (call.name === 'query') return view.method === params.method;
				if (typeof collection !== 'string') return false;
				const records = Array.isArray(view.records) ? view.records : [];
				return view.collection === collection || records.some((r) => isObject(r) && r.collection === collection);
			}) ?? null
		);
	}

	/** Say what a drawing opened, which the playground does not follow. */
	open(call: Call) {
		this.opened = { call, tool: isTool(call.name) ? call.name : null, template: isTool(call.name) ? this.templateOf(call) : null };
	}

	/** Take up the call a drawing opened, with the view that draws it, where a bundled one does. */
	follow(opened: Opened) {
		if (!opened.tool) return;
		if (opened.template) this.#begin(opened.tool, opened.call.args, opened.template.view, opened.template.name);
		else {
			const { view: _, ...rest } = opened.call.args;
			this.tool = opened.tool;
			this.args = pretty(rest);
			this.opened = null;
		}
	}

	/**
	 * Draw the work: nothing while the call or the view is not JSON (its
	 * editor says why); afresh when what reads changed since the answer was
	 * read, or `fresh`; else over the answer.
	 */
	async draw(fresh = false): Promise<void> {
		const args = this.call;
		const view = this.document;
		if (!args || !view) return;
		const { view: _, ...rest } = args;
		const tool = this.tool;
		const bare = structuredClone(view);
		for (const mode of MODES) if (isObject(bare[mode])) delete bare[mode].layout;
		const key = JSON.stringify({ tool, args: rest, view: bare });
		const call: Call = { name: tool, args: rest };
		const before = !fresh && this.answer?.key === key ? this.answer : null;
		const current = ++this.#generation;

		if (before?.failure) {
			this.problems = [];
			this.entry = { view: read(before.failure), call };
			return;
		}
		this.busy = true;
		try {
			const input = { tool, arguments: { ...rest, view } as previewView.$InputBody['arguments'], ...(before && { answer: before.data as previewView.$InputBody['answer'] }) };
			const out = await procedure<typeof previewView.main>('place.hud.previewView', input);
			if (current !== this.#generation) return;
			if (out.problems?.length) {
				this.problems = out.problems.map(({ at, message }) => ({ at, message }));
				return;
			}
			this.problems = [];
			const at = new Date().toISOString();
			if (before && out.ui) {
				this.entry = { view: read({ structuredContent: before.data, _meta: { ui: out.ui } }), call };
				this.status = { how: 'drawn', at, read: before.at, viewer: before.viewer };
			} else if (out.result) {
				const result = out.result as ToolResult;
				this.answer = { key, data: result.structuredContent, summary: text(result), viewer: viewer(result), at, failure: result.isError ? result : null };
				this.entry = { view: read(result), call };
				this.status = { how: 'read', at, read: at, viewer: this.answer.viewer };
			}
		} catch (error) {
			if (current !== this.#generation) return;
			if (before && error instanceof XrpcError && error.error === 'InvalidRequest') {
				// The answer is not of this call after all: read it afresh.
				this.answer = null;
				return this.draw(true);
			}
			this.entry = { view: { renderer: 'error', message: errorText(error) }, call };
			this.status = null;
		} finally {
			if (current === this.#generation) this.busy = false;
		}
	}
}