repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ui/widget-state.ts

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

export type WidgetRecord = {
	widgetId: string;
	toolCallId: string;
	title: string;
	fallback: string;
	html: string;
	status: "mounted" | "updated" | "action" | "error";
	audit: UiWidgetEvent[];
};

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

export type MountWidgetInput = {
	toolCallId: string;
	title: string;
	fallback: string;
	html: string;
};

export type WidgetActionInput = {
	toolCallId: string;
	label: string;
	payload?: unknown;
};

export class WidgetStore {
	readonly #now: () => number;
	#actions = 0;
	#widgets = new Map<string, WidgetRecord>();

	constructor(options: WidgetStoreOptions = {}) {
		this.#now = options.now ?? Date.now;
	}

	mount(input: MountWidgetInput): UiWidgetEvent {
		const widgetId = widgetIdForToolCall(input.toolCallId);
		const event: UiWidgetEvent = {
			id: 0,
			at: this.#now(),
			type: "widget_mount",
			widgetId,
			toolCallId: input.toolCallId,
			title: input.title,
			fallback: input.fallback,
			html: input.html,
			status: "mounted",
		};
		this.#widgets.set(widgetId, {
			widgetId,
			toolCallId: input.toolCallId,
			title: input.title,
			fallback: input.fallback,
			html: input.html,
			status: "mounted",
			audit: [event],
		});
		return event;
	}

	update(widgetId: string, patch: { html: string }): UiWidgetEvent {
		const record = this.#require(widgetId);
		record.html = patch.html;
		record.status = "updated";
		return this.#audit(record, {
			type: "widget_update",
			widgetId,
			toolCallId: record.toolCallId,
			html: patch.html,
			status: "updated",
		});
	}

	action(widgetId: string, input: WidgetActionInput): UiWidgetEvent {
		const record = this.#require(widgetId);
		record.status = "action";
		return this.#audit(record, {
			type: "widget_action",
			widgetId,
			toolCallId: input.toolCallId,
			actionId: `action-${++this.#actions}`,
			label: input.label,
			payload: input.payload,
			status: "action",
		});
	}

	error(widgetId: string, message: string): UiWidgetEvent {
		const record = this.#require(widgetId);
		record.status = "error";
		return this.#audit(record, {
			type: "widget_error",
			widgetId,
			toolCallId: record.toolCallId,
			message,
			status: "error",
		});
	}

	get(widgetId: string): WidgetRecord | undefined {
		return this.#widgets.get(widgetId);
	}

	#audit(
		record: WidgetRecord,
		event: Omit<UiWidgetEvent, "id" | "at">,
	): UiWidgetEvent {
		const full = { id: 0, at: this.#now(), ...event };
		record.audit.push(full);
		return full;
	}

	#require(widgetId: string): WidgetRecord {
		const record = this.#widgets.get(widgetId);
		if (!record) throw new Error(`Unknown widget: ${widgetId}`);
		return record;
	}
}

export function widgetIdForToolCall(toolCallId: string): string {
	return `widget-${toolCallId.replaceAll(/[^a-zA-Z0-9_-]/g, "-")}`;
}