repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ui/lifecycle.ts

Raw
File outline
import type { UiEventInput } from "./protocol";

export type LifecycleTrackerOptions = {
	now?: () => number;
	heartbeatMs?: number;
};

export class LifecycleTracker {
	readonly #now: () => number;
	readonly #heartbeatMs: number;
	#clients = new Map<string, number>();
	#reported = new Set<string>();

	constructor(options: LifecycleTrackerOptions = {}) {
		this.#now = options.now ?? Date.now;
		this.#heartbeatMs = options.heartbeatMs ?? 15_000;
	}

	heartbeat(clientId: string, at = this.#now()): void {
		this.#clients.set(clientId, at);
		this.#reported.delete(clientId);
	}

	check(): UiEventInput[] {
		const now = this.#now();
		const events: UiEventInput[] = [];
		for (const [clientId, at] of this.#clients) {
			if (now - at <= this.#heartbeatMs || this.#reported.has(clientId))
				continue;
			events.push(lifecycleError(clientId, "browser heartbeat lost"));
			this.#reported.add(clientId);
		}
		return events;
	}

	close(clientId: string): UiEventInput {
		this.#clients.delete(clientId);
		return lifecycleError(clientId, "browser websocket closed");
	}

	pagehide(clientId: string): UiEventInput {
		return lifecycleError(clientId, "browser page hidden/unloaded");
	}

	stale(clientId: string): UiEventInput {
		return lifecycleError(clientId, "browser client stale");
	}

	reconnect(clientId: string): UiEventInput {
		this.heartbeat(clientId);
		return {
			type: "log",
			level: "info",
			message: `browser reconnected: ${clientId}`,
		};
	}
}

function lifecycleError(clientId: string, message: string): UiEventInput {
	return {
		type: "error",
		message,
		action: "reload /ui browser tab or run /ui open",
		retryable: true,
		clientId,
		agentHint:
			"wait for browser reconnect before relying on widget interaction",
	};
}