repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

Add ui browser lifecycle events

392e61dabcfe4c71bf58a142d57a042d381da42c

Oliver Krylow <o.krylow@isp-insoft.de> ·

unsigned

Browse filesCompare with HEAD

Changed files (6)

extensions/ui/__tests__/lifecycle.test.ts

Added
new file mode 100644
1 +import { describe, expect, it } from "vitest";
2 +import { LifecycleTracker } from "../lifecycle";
4 +describe("ui browser lifecycle", () => {
5 + it("emits heartbeat timeout errors", () => {
6 + const tracker = new LifecycleTracker({
7 + now: () => 10_000,
8 + heartbeatMs: 5_000,
9 + });
10 + tracker.heartbeat("client-1", 1_000);
11 + expect(tracker.check()).toEqual([
12 + expect.objectContaining({
13 + type: "error",
14 + clientId: "client-1",
15 + message: "browser heartbeat lost",
16 + retryable: true,
17 + }),
18 + ]);
19 + });
21 + it("emits close pagehide stale and reconnect lifecycle events", () => {
22 + const tracker = new LifecycleTracker({ now: () => 20 });
23 + expect(tracker.close("client-1")).toMatchObject({
24 + type: "error",
25 + message: "browser websocket closed",
26 + });
27 + expect(tracker.pagehide("client-1")).toMatchObject({
28 + type: "error",
29 + message: "browser page hidden/unloaded",
30 + });
31 + expect(tracker.stale("client-1")).toMatchObject({
32 + type: "error",
33 + message: "browser client stale",
34 + });
35 + expect(tracker.reconnect("client-1")).toMatchObject({
36 + type: "log",
37 + message: "browser reconnected: client-1",
38 + });
39 + });
40 +});

extensions/ui/lifecycle.ts

Added
new file mode 100644
1 +import type { UiEventInput } from "./protocol";
3 +export type LifecycleTrackerOptions = {
4 + now?: () => number;
5 + heartbeatMs?: number;
6 +};
8 +export class LifecycleTracker {
9 + readonly #now: () => number;
10 + readonly #heartbeatMs: number;
11 + #clients = new Map<string, number>();
12 + #reported = new Set<string>();
14 + constructor(options: LifecycleTrackerOptions = {}) {
15 + this.#now = options.now ?? Date.now;
16 + this.#heartbeatMs = options.heartbeatMs ?? 15_000;
17 + }
19 + heartbeat(clientId: string, at = this.#now()): void {
20 + this.#clients.set(clientId, at);
21 + this.#reported.delete(clientId);
22 + }
24 + check(): UiEventInput[] {
25 + const now = this.#now();
26 + const events: UiEventInput[] = [];
27 + for (const [clientId, at] of this.#clients) {
28 + if (now - at <= this.#heartbeatMs || this.#reported.has(clientId))
29 + continue;
30 + events.push(lifecycleError(clientId, "browser heartbeat lost"));
31 + this.#reported.add(clientId);
32 + }
33 + return events;
34 + }
36 + close(clientId: string): UiEventInput {
37 + this.#clients.delete(clientId);
38 + return lifecycleError(clientId, "browser websocket closed");
39 + }
41 + pagehide(clientId: string): UiEventInput {
42 + return lifecycleError(clientId, "browser page hidden/unloaded");
43 + }
45 + stale(clientId: string): UiEventInput {
46 + return lifecycleError(clientId, "browser client stale");
47 + }
49 + reconnect(clientId: string): UiEventInput {
50 + this.heartbeat(clientId);
51 + return {
52 + type: "log",
53 + level: "info",
54 + message: `browser reconnected: ${clientId}`,
55 + };
56 + }
59 +function lifecycleError(clientId: string, message: string): UiEventInput {
60 + return {
61 + type: "error",
62 + message,
63 + action: "reload /ui browser tab or run /ui open",
64 + retryable: true,
65 + clientId,
66 + agentHint:
67 + "wait for browser reconnect before relying on widget interaction",
68 + };

extensions/ui/protocol.ts

Modified
45 45 message: string;
46 46 action: string;
47 47 retryable: boolean;
48 + clientId?: string;
49 + agentHint?: string;
50 + relatedId?: string;
50 53 export type UiRequestEvent = UiEventBase & {

extensions/ui/runtime.ts

Modified
13 13 extensionUiResponseCommand,
14 14 isExtensionUiRequest,
15 15 } from "./extension-ui";
16 +import { LifecycleTracker } from "./lifecycle";
16 17 import { chooseLanAddress } from "./network";
17 18 import { openBrowser } from "./open";
18 19 import { renderQr } from "./qr";
63 64 let rpcState: string | undefined;
64 65 const events = options.events ?? new EventStore();
65 66 const telemetry = new TelemetryAggregator();
67 + const lifecycle = new LifecycleTracker();
68 + const lifecycleTimer = setInterval(() => {
69 + for (const event of lifecycle.check()) publish(event);
70 + }, 5_000);
71 + if (typeof lifecycleTimer.unref === "function") lifecycleTimer.unref();
67 73 const publish = (input: Parameters<EventStore["append"]>[0]) => {
68 74 const event = events.append(input);
102 108 events,
103 109 snapshotStatus: rpcState ? mapRpcState(rpcState) : "waiting",
104 110 onBrowserMessage: async (message) => {
105 - await handleBrowserMessage(message, rpc, publish, telemetry);
111 + await handleBrowserMessage(message, rpc, publish, telemetry, lifecycle);
107 113 onClientState: () => {
108 114 state = currentStatus();
153 159 await openBrowser(server.publicUrl);
155 161 async stop(reason: string) {
162 + clearInterval(lifecycleTimer);
156 163 const currentServer = server;
157 164 const currentRpc = rpc;
158 165 server = undefined;
170 177 rpc: RpcClient | undefined,
171 178 publish: (input: Parameters<EventStore["append"]>[0]) => unknown,
172 179 telemetry: TelemetryAggregator,
180 + lifecycle: LifecycleTracker,
173 181 ): Promise<void> {
174 182 if (!rpc || !isBrowserMessage(message)) return;
175 183 if (message.type === "abort") {
194 202 publish({ type: "log", level: "info", message: "toggle expand requested" });
195 203 return;
205 + if (message.type === "lifecycle_heartbeat") {
206 + lifecycle.heartbeat(message.clientId);
207 + return;
209 + if (message.type === "lifecycle_reconnect") {
210 + publish(lifecycle.reconnect(message.clientId));
211 + return;
213 + if (message.type === "lifecycle_close") {
214 + publish(lifecycle.close(message.clientId));
215 + return;
217 + if (message.type === "lifecycle_pagehide") {
218 + publish(lifecycle.pagehide(message.clientId));
219 + return;
197 221 if (message.type === "telemetry_batch") {
198 222 for (const event of message.events) telemetry.add(event);
199 223 publish({
270 294 | { type: "cycle-model" }
271 295 | { type: "toggle-expand" }
272 296 | { type: "telemetry_batch"; events: TelemetryEvent[] }
297 + | { type: "lifecycle_heartbeat"; clientId: string }
298 + | { type: "lifecycle_reconnect"; clientId: string }
299 + | { type: "lifecycle_close"; clientId: string }
300 + | { type: "lifecycle_pagehide"; clientId: string }
273 301 | ({ type: "ui_response"; id: string } & (
274 302 | { value: string }
275 303 | { confirmed: boolean }
292 320 return typeof (value as { text?: unknown }).text === "string";
293 321 if (type === "telemetry_batch")
294 322 return Array.isArray((value as { events?: unknown }).events);
323 + if (
324 + type === "lifecycle_heartbeat" ||
325 + type === "lifecycle_reconnect" ||
326 + type === "lifecycle_close" ||
327 + type === "lifecycle_pagehide"
329 + return typeof (value as { clientId?: unknown }).clientId === "string";
295 330 if (type === "ui_response")
296 331 return typeof (value as { id?: unknown }).id === "string";
297 332 if (type === "widget_action")

extensions/ui/server.ts

Modified
47 47 const host = listenHostFor(options.address);
48 48 let currentState: UiServerState = "waiting";
49 49 let clientCount = 0;
50 + let clientSeq = 0;
50 51 let closed = false;
51 52 const sockets = new Set<WebSocket>();
52 53 const wss = new WebSocketServer({ noServer: true });
76 77 return;
78 79 wss.handleUpgrade(req, socket, head, (ws) => {
80 + const clientId = `client-${++clientSeq}`;
79 81 sockets.add(ws);
80 82 clientCount += 1;
81 83 currentState = "connected";
82 84 options.onClientState?.("connected");
85 + void options.onBrowserMessage?.({
86 + type: "lifecycle_reconnect",
87 + clientId,
88 + });
83 89 const after = Number(url.searchParams.get("after") ?? 0);
84 90 ws.send(
85 91 JSON.stringify({
92 98 ws.on("message", (data) => {
93 99 try {
94 - void options.onBrowserMessage?.(JSON.parse(String(data)));
100 + const message = JSON.parse(String(data));
101 + if (
102 + message &&
103 + typeof message === "object" &&
104 + !("clientId" in message)
105 + ) {
106 + message.clientId = clientId;
108 + void options.onBrowserMessage?.(message);
95 109 } catch {
96 110 ws.send(JSON.stringify({ type: "error", message: "invalid json" }));
99 - ws.on("close", () => sockets.delete(ws));
113 + ws.on("close", () => {
114 + sockets.delete(ws);
115 + void options.onBrowserMessage?.({ type: "lifecycle_close", clientId });
116 + });

extensions/ui/web/app.js.ts

Modified
66 66 const payload = JSON.parse(event.data);
67 67 if (payload.type === 'events') renderEvents(payload.events || []);
69 - socket.addEventListener('open', () => { status.textContent = 'connected'; });
69 + socket.addEventListener('open', () => {
70 + status.textContent = 'connected';
71 + socket.send(JSON.stringify({ type: 'lifecycle_heartbeat' }));
72 + setInterval(() => socket?.readyState === WebSocket.OPEN && socket.send(JSON.stringify({ type: 'lifecycle_heartbeat' })), 5000);
73 + });
70 74 socket.addEventListener('close', () => { status.textContent = 'disconnected'; });
130 134 window.addEventListener('focus', event => trackTelemetry({ type: 'focus', target: targetLabel(event.target) }), true);
131 135 window.addEventListener('blur', event => trackTelemetry({ type: 'blur', target: targetLabel(event.target) }), true);
132 136 document.addEventListener('selectionchange', () => trackTelemetry({ type: 'selection', text: String(getSelection() || '') }));
133 -window.addEventListener('pagehide', () => trackTelemetry({ type: 'pagehide' }));
137 +window.addEventListener('pagehide', () => {
138 + trackTelemetry({ type: 'pagehide' });
139 + socket?.send(JSON.stringify({ type: 'lifecycle_pagehide' }));
140 +});
134 141 form.addEventListener('submit', () => trackTelemetry({ type: 'form', formId: 'composer', state: 'submit' }));
136 143 form.addEventListener('submit', event => {