chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.3.1 Latest 5 packages
0
0
// What happens on every canvas a person has open as a tab, from one
// stream: place.hud.getWorkspaceEvents, server-sent events, each
// `data:` a JSON object typed by its `$type` (a defs event): a tile added,
// changed or removed, who is on a canvas now, and a nudge that the
// workspace changed. One stream for them all, as a browser allows only six
// connections to an origin. The stream follows the open tabs itself.
import type { CanvasesEvent, PresenceEvent, TileEvent } from './model';
export type Listeners = {
tile: (event: TileEvent) => void;
presence: (event: PresenceEvent) => void;
canvases: (event: CanvasesEvent) => void;
/** Each time the stream opens: what changed while it was down is to be caught up. */
opened: () => void;
/** The stream was refused: whether the session is still there is to be asked, which finds a sign-out. */
refused: () => Promise<boolean>;
};
/** How long a refused stream waits before it is tried again. */
const RETRY_MS = 5000;
/** Hear the workspace until the returned function is called. The browser
* reconnects a dropped stream itself; one the server refuses is tried again
* after `refused` says the session is still there. */
export function workspaceEvents(listeners: Listeners): () => void {
let source: EventSource | null = null;
let timer: number | null = null;
let stopped = false;
const open = () => {
source = new EventSource('/xrpc/place.hud.getWorkspaceEvents');
source.onmessage = (message) => {
let event: unknown;
try {
event = JSON.parse(message.data);
} catch {
return;
}
if (typeof event !== 'object' || event === null || !('$type' in event)) return;
switch (event.$type) {
case 'place.hud.defs#tileEvent':
listeners.tile(event as TileEvent);
break;
case 'place.hud.defs#presenceEvent':
listeners.presence(event as PresenceEvent);
break;
case 'place.hud.defs#canvasesEvent':
listeners.canvases(event as CanvasesEvent);
break;
}
};
source.onopen = () => listeners.opened();
source.onerror = () => {
if (source?.readyState !== EventSource.CLOSED) return;
source = null;
timer = window.setTimeout(() => {
timer = null;
void listeners.refused().then((still) => {
if (still && !stopped) open();
});
}, RETRY_MS);
};
};
open();
return () => {
stopped = true;
source?.close();
if (timer !== null) window.clearTimeout(timer);
};
}