~ 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
195 lines · 7.7 KB Raw History
// Screens read ahead, so the one tapped draws at once: a link's call is
// made as a pointer rests on it, as it is pressed (before the click that
// opens it lands), and, on a screen with no pointer that hovers (a
// phone's), as it shows a while in the viewport. Its answer is kept
// briefly, for the screen that opens it to take. The links are the
// renderer's `<a href>`s, each a call whose URL the app's routes give
// (`hrefOf`): `calls` is each such URL's call. A router's own preloading
// should be off (SvelteKit's `data-sveltekit-preload-*`): it would load
// the page for a URL, which the stack does not draw from once the app is
// running, and keeps one answer. The viewport reads ahead only once the
// page has loaded and the browser is idle, a few calls at a time, so it
// never crowds out what the page loads first (its pictures, its code), and
// never of a screen out of reach (`inert`, under the one on top) until it
// is in reach again.

import type { Call, ToolResult } from '@hud/shared/result';
import type { Client } from './client';

/** How long an answer read ahead is good for. */
const FRESH = 30_000;
/** The most answers kept at once, and the most a viewport reads ahead of a screen. */
const KEPT = 40;
const SHOWN = 8;
/** How many of a viewport's calls are on their way at once: the rest wait their turn. */
const AT_ONCE = 2;
/** How long a pointer rests, or a link shows, before its call is made. */
const REST = 60;
const SHOWING = 400;
/** The longest the viewport waits for the browser to be idle once the page has loaded, and where a browser can't say, how long it waits instead. */
const IDLE = 2_000;
const SETTLING = 500;

/** Calls `then` once the page has loaded and the browser is idle; the returned function calls it off. */
function settled(then: () => void): () => void {
	let idle: number | undefined;
	let timer: ReturnType<typeof setTimeout> | undefined;
	const loaded = () => {
		if (typeof requestIdleCallback === 'function') idle = requestIdleCallback(then, { timeout: IDLE });
		else timer = setTimeout(then, SETTLING);
	};
	if (document.readyState === 'complete') loaded();
	else addEventListener('load', loaded, { once: true });
	return () => {
		removeEventListener('load', loaded);
		if (idle !== undefined) cancelIdleCallback(idle);
		clearTimeout(timer);
	};
}

/** The answers read ahead of their screens, in a page's memory. */
export class Ahead {
	readonly #kept = new Map<string, { result: Promise<ToolResult>; at: number }>();
	readonly #client: Client;
	/** A viewport's calls waiting their turn, and how many are on their way. */
	readonly #waiting: Call[] = [];
	#going = 0;

	constructor(client: Client) {
		this.#client = client;
	}

	/** Make a call ahead of its screen, unless made a moment ago: its answer, or null where it was. */
	prefetch(call: Call): Promise<ToolResult> | null {
		const key = JSON.stringify(call);
		const now = Date.now();
		const was = this.#kept.get(key);
		if (was && now - was.at < FRESH) return null;
		const result = this.#client.callTool(call.name, call.args);
		result.catch(() => this.#kept.delete(key));
		this.#kept.delete(key);
		this.#kept.set(key, { result, at: now });
		if (this.#kept.size > KEPT) this.#kept.delete(this.#kept.keys().next().value!);
		return result;
	}

	/** The viewport's calls waiting made in their turn, `AT_ONCE` on their way at most. */
	#next() {
		while (this.#going < AT_ONCE && this.#waiting.length > 0) {
			const result = this.prefetch(this.#waiting.shift()!);
			if (!result) continue;
			this.#going++;
			void result
				.catch(() => undefined)
				.finally(() => {
					this.#going--;
					this.#next();
				});
		}
	}

	/** A call's answer read ahead, taken for its screen; null where there is none fresh. */
	take(call: Call): Promise<ToolResult> | null {
		const key = JSON.stringify(call);
		const was = this.#kept.get(key);
		this.#kept.delete(key);
		return was && Date.now() - was.at < FRESH ? was.result : null;
	}

	/** Every answer read ahead let go: the account wrote, or signed out, so they may show what changed. */
	forget() {
		this.#kept.clear();
	}

	/** Read ahead the links in `element` whose URL `calls` holds: on hover and press, and on a screen with no hover, as they show, once the page has loaded. An attachment. */
	readAhead(calls: Map<string, Call>) {
		return (element: HTMLElement) => {
			const callAt = (target: EventTarget | null) => {
				const link = target instanceof Element ? target.closest('a[href]') : null;
				return link ? (calls.get(link.getAttribute('href')!) ?? null) : null;
			};
			let resting: ReturnType<typeof setTimeout> | undefined;
			const over = (event: PointerEvent) => {
				clearTimeout(resting);
				const call = event.pointerType === 'mouse' ? callAt(event.target) : null;
				if (call) resting = setTimeout(() => this.prefetch(call), REST);
			};
			const press = (event: Event) => {
				const call = callAt(event.target);
				if (call) this.prefetch(call);
			};
			element.addEventListener('pointerover', over);
			element.addEventListener('pointerdown', press);

			const saving = (navigator as Navigator & { connection?: { saveData?: boolean } }).connection?.saveData === true;
			let stop = () => {};
			if (!saving && matchMedia('(hover: none)').matches) {
				const timers = new Map<Element, ReturnType<typeof setTimeout>>();
				/** The links read ahead already, never watched again. */
				const done = new WeakSet<Element>();
				let read = 0;
				const seen = new IntersectionObserver(
					(entries) => {
						for (const entry of entries) {
							clearTimeout(timers.get(entry.target));
							timers.delete(entry.target);
							if (!entry.isIntersecting || read >= SHOWN || entry.target.closest('[inert]')) continue;
							const call = callAt(entry.target);
							if (!call) continue;
							timers.set(
								entry.target,
								setTimeout(() => {
									seen.unobserve(entry.target);
									if (read >= SHOWN || entry.target.closest('[inert]')) return;
									done.add(entry.target);
									read++;
									this.#waiting.push(call);
									this.#next();
								}, SHOWING)
							);
						}
					},
					{ threshold: 0.5 }
				);
				const watch = (root: ParentNode) => root.querySelectorAll('a[href]').forEach((link) => seen.observe(link));
				// A screen uncovered (its `inert` let go, the one over it gone) is watched afresh: its links already in view, passed over while it was out of reach, are seen again.
				const added = new MutationObserver((changes) => {
					for (const change of changes) {
						if (change.type === 'attributes') {
							if (change.target instanceof Element && !change.target.closest('[inert]'))
								change.target.querySelectorAll('a[href]').forEach((link) => {
									if (done.has(link)) return;
									seen.unobserve(link);
									seen.observe(link);
								});
							continue;
						}
						for (const node of change.addedNodes) if (node instanceof Element) (node.matches('a[href]') ? seen.observe(node) : watch(node));
					}
				});
				// Once the page has loaded and the browser is idle: before, its own pictures and code come first.
				const waiting = settled(() => {
					watch(element);
					added.observe(element, { childList: true, subtree: true, attributes: true, attributeFilter: ['inert'] });
				});
				// A new screen shown reads ahead of its own: the count starts again as the URL changes.
				const moved = () => (read = 0);
				addEventListener('popstate', moved);
				stop = () => {
					waiting();
					seen.disconnect();
					added.disconnect();
					removeEventListener('popstate', moved);
					for (const timer of timers.values()) clearTimeout(timer);
					this.#waiting.length = 0;
				};
			}
			return () => {
				clearTimeout(resting);
				element.removeEventListener('pointerover', over);
				element.removeEventListener('pointerdown', press);
				stop();
			};
		};
	}
}