commit 6c9d46b4b0bb17c68f045029a95a78c56c55cae9
parent b294961132e9d03b6f5b6c95d10dc503c9b06d0f
Author: Florian Dold <dold@taler.net>
Date: Tue, 10 Nov 2026 16:58:45 +0100
wallet web UI: manage typed observations and port ownership
Own one registration per view, with explicit loading, ready, disconnected,
failed and deleted states. Reconnect with a fresh ID and clean up late
registrations and disconnected extension ports.
Diffstat:
4 files changed, 486 insertions(+), 3 deletions(-)
diff --git a/packages/wallet-webui/src/api/observations.ts b/packages/wallet-webui/src/api/observations.ts
@@ -0,0 +1,174 @@
+/*
+ * This file is part of GNU Taler
+ * (C) 2026 Taler Systems S.A.
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+import {
+ NotificationType,
+ type PeerPushCreditSnapshot,
+ type TransactionIdStr,
+} from "@gnu-taler/taler-util";
+import { WalletApiOperation } from "@gnu-taler/taler-wallet-core";
+import { useEffect, useRef, useState } from "preact/hooks";
+import type { WalletConnection } from "./contracts.js";
+import { i18n } from "../i18n/runtime.js";
+
+export type PeerCreditObservationState =
+ | { status: "loading"; snapshot?: PeerPushCreditSnapshot }
+ | { status: "ready"; snapshot: PeerPushCreditSnapshot }
+ | { status: "disconnected"; snapshot?: PeerPushCreditSnapshot }
+ | { status: "failed"; error: Error; snapshot?: PeerPushCreditSnapshot }
+ | { status: "deleted" };
+
+/** Owns one UI subscription; registration acknowledgements never carry state. */
+export class PeerCreditObservation {
+ state: PeerCreditObservationState = { status: "loading" };
+ private id?: string;
+ private revision = 0;
+ private connected = false;
+ private disposed = false;
+ private unsubscribeNotifications: () => void;
+ private unsubscribeStatus: () => void;
+
+ constructor(
+ private connection: WalletConnection,
+ private transactionId: TransactionIdStr,
+ private changed: (state: PeerCreditObservationState) => void,
+ private newId: () => string = () => crypto.randomUUID(),
+ ) {
+ this.unsubscribeNotifications = connection.subscribeNotifications((n) => {
+ if (
+ this.disposed ||
+ !this.id ||
+ !("observationId" in n) ||
+ n.observationId !== this.id
+ )
+ return;
+ if (
+ n.type === NotificationType.ObservationSnapshot &&
+ n.observationType === "peer-push-credit"
+ ) {
+ if (
+ n.transactionId !== this.transactionId ||
+ n.revision <= this.revision
+ )
+ return;
+ this.revision = n.revision;
+ this.update(
+ n.snapshot === null
+ ? { status: "deleted" }
+ : { status: "ready", snapshot: n.snapshot },
+ );
+ if (n.snapshot === null) this.id = undefined;
+ } else if (n.type === NotificationType.ObservationError) {
+ this.id = undefined;
+ this.update({
+ status: "failed",
+ snapshot: this.snapshot(),
+ error: new Error(
+ n.error.hint ??
+ n.error.message ??
+ i18n.str`Transaction updates stopped.`,
+ ),
+ });
+ }
+ });
+ this.unsubscribeStatus = connection.subscribeStatus((status) => {
+ const wasConnected = this.connected;
+ this.connected = status.state === "connected";
+ if (this.state.status === "deleted" || this.disposed) return;
+ if (this.connected) {
+ if (!wasConnected) this.retry();
+ } else {
+ this.stop();
+ this.update({ status: "disconnected", snapshot: this.snapshot() });
+ }
+ });
+ }
+
+ private snapshot() {
+ return this.state.status === "deleted" ? undefined : this.state.snapshot;
+ }
+
+ private update(state: PeerCreditObservationState) {
+ this.state = state;
+ if (!this.disposed) this.changed(state);
+ }
+
+ private stop() {
+ const id = this.id;
+ this.id = undefined;
+ if (id)
+ void this.connection.client
+ .call(WalletApiOperation.StopObservation, { observationId: id })
+ .catch(() => {});
+ }
+
+ retry = () => {
+ if (this.disposed || !this.connected || this.state.status === "deleted")
+ return;
+ this.stop();
+ const id = (this.id = this.newId());
+ this.revision = 0;
+ this.update({ status: "loading", snapshot: this.snapshot() });
+ void this.connection.client
+ .call(WalletApiOperation.ObservePeerPushCredit, {
+ transactionId: this.transactionId,
+ observationId: id,
+ })
+ .then(() => {
+ // stop may have arrived before a delayed registration was installed.
+ if (this.disposed || this.id !== id) {
+ void this.connection.client
+ .call(WalletApiOperation.StopObservation, { observationId: id })
+ .catch(() => {});
+ }
+ })
+ .catch((error: unknown) => {
+ if (this.disposed || this.id !== id) return;
+ this.stop();
+ this.update({
+ status: "failed",
+ snapshot: this.snapshot(),
+ error: error instanceof Error ? error : new Error(String(error)),
+ });
+ });
+ };
+
+ dispose() {
+ this.disposed = true;
+ this.unsubscribeNotifications();
+ this.unsubscribeStatus();
+ this.stop();
+ }
+}
+
+export function usePeerCreditObservation(
+ connection: WalletConnection,
+ transactionId: TransactionIdStr,
+) {
+ const [value, setValue] = useState<{
+ connection: WalletConnection;
+ transactionId: TransactionIdStr;
+ state: PeerCreditObservationState;
+ }>();
+ const controller = useRef<PeerCreditObservation>();
+ useEffect(() => {
+ const instance = new PeerCreditObservation(
+ connection,
+ transactionId,
+ (state) => setValue({ connection, transactionId, state }),
+ );
+ controller.current = instance;
+ return () => {
+ instance.dispose();
+ controller.current = undefined;
+ };
+ }, [connection, transactionId]);
+ const state: PeerCreditObservationState =
+ value?.connection === connection && value.transactionId === transactionId
+ ? value.state
+ : { status: "loading" };
+ return { state, retry: () => controller.current?.retry() };
+}
diff --git a/packages/wallet-webui/src/platform/extension-background.ts b/packages/wallet-webui/src/platform/extension-background.ts
@@ -1,4 +1,5 @@
/// <reference types="chrome" />
+import { ObservationOwner } from "./observation-owner.js";
import { Result, TalerUriAction, TalerUris } from "@gnu-taler/taler-util";
import {
BROWSER_RPC_VERSION,
@@ -21,6 +22,12 @@ import {
} from "./page-integration.js";
const ports = new Set<chrome.runtime.Port>();
+const observationOwners = new Map<chrome.runtime.Port, ObservationOwner>();
+function disconnectPort(port: chrome.runtime.Port) {
+ ports.delete(port);
+ observationOwners.get(port)?.close();
+ observationOwners.delete(port);
+}
const inbox = new StoredActionInbox(new ExtensionSessionActionStore());
let hostPromise: Promise<RunningWalletHost> | undefined;
@@ -33,7 +40,7 @@ function sendToPort(
port.postMessage(message);
return true;
} catch {
- ports.delete(port);
+ disconnectPort(port);
return false;
}
}
@@ -63,7 +70,11 @@ function getHost(): Promise<RunningWalletHost> {
chrome.runtime.onConnect.addListener((port) => {
if (port.name !== "wallet-ui-v1") return;
ports.add(port);
- port.onDisconnect.addListener(() => ports.delete(port));
+ const owner = new ObservationOwner(async (request) =>
+ (await getHost()).handle(request),
+ );
+ observationOwners.set(port, owner);
+ port.onDisconnect.addListener(() => disconnectPort(port));
sendToPort(port, {
version: BROWSER_RPC_VERSION,
kind: "status",
@@ -92,7 +103,7 @@ chrome.runtime.onConnect.addListener((port) => {
return;
let response;
try {
- response = await (await getHost()).handle(message.request);
+ response = await owner.handle(message.request);
} catch {
response = unavailableCoreResponse(
message.request,
diff --git a/packages/wallet-webui/src/platform/observation-owner.ts b/packages/wallet-webui/src/platform/observation-owner.ts
@@ -0,0 +1,55 @@
+/*
+ * This file is part of GNU Taler
+ * (C) 2026 Taler Systems S.A.
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+import type {
+ CoreApiRequestEnvelope,
+ CoreApiResponse,
+} from "@gnu-taler/taler-util";
+import { WalletApiOperation } from "@gnu-taler/taler-wallet-core";
+
+/** Cleans up subscriptions even when the port closes during registration. */
+export class ObservationOwner {
+ private ids = new Set<string>();
+ private closed = false;
+ constructor(
+ private dispatch: (
+ request: CoreApiRequestEnvelope,
+ ) => Promise<CoreApiResponse>,
+ ) {}
+
+ async handle(request: CoreApiRequestEnvelope): Promise<CoreApiResponse> {
+ const args = request.args as { observationId?: unknown } | undefined;
+ const id =
+ typeof args?.observationId === "string" ? args.observationId : undefined;
+ const registering =
+ request.operation === WalletApiOperation.ObservePeerPushCredit &&
+ id !== undefined;
+ const response = await this.dispatch(request);
+ if (registering && response.type !== "error") {
+ if (this.closed) this.stop(id);
+ else this.ids.add(id);
+ }
+ if (
+ request.operation === WalletApiOperation.StopObservation &&
+ id &&
+ response.type !== "error"
+ )
+ this.ids.delete(id);
+ return response;
+ }
+ private stop(id: string) {
+ void this.dispatch({
+ id: `stop-${id}`,
+ operation: WalletApiOperation.StopObservation,
+ args: { observationId: id },
+ }).catch(() => {});
+ }
+ close() {
+ this.closed = true;
+ for (const id of this.ids) this.stop(id);
+ this.ids.clear();
+ }
+}
diff --git a/packages/wallet-webui/test/observations.test.ts b/packages/wallet-webui/test/observations.test.ts
@@ -0,0 +1,243 @@
+/*
+ * This file is part of GNU Taler
+ * (C) 2026 Taler Systems S.A.
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ NotificationType,
+ ObservationType,
+ TransactionType,
+ TransactionMajorState,
+ TransactionMinorState,
+ type WalletNotification,
+ type PeerPushCreditSnapshot,
+ type TransactionIdStr,
+ type CoreApiRequestEnvelope,
+ type CoreApiResponse,
+} from "@gnu-taler/taler-util";
+import { WalletApiOperation } from "@gnu-taler/taler-wallet-core";
+import { PeerCreditObservation } from "../src/api/observations.js";
+import type {
+ ConnectionStatus,
+ WalletConnection,
+} from "../src/api/contracts.js";
+import { ObservationOwner } from "../src/platform/observation-owner.js";
+
+const transactionId = "txn:peer-push-credit:test" as TransactionIdStr;
+const snapshot: PeerPushCreditSnapshot = {
+ transaction: {
+ type: TransactionType.PeerPushCredit,
+ transactionId,
+ timestamp: { t_s: 1 },
+ scopes: [],
+ txState: {
+ major: TransactionMajorState.Pending,
+ minor: TransactionMinorState.KycRequired,
+ },
+ txActions: [],
+ amountRaw: "KUDOS:5",
+ amountEffective: "KUDOS:4.8",
+ info: { summary: "Lunch", expiration: undefined, iconId: undefined },
+ exchangeBaseUrl: "https://exchange.example/",
+ kycUrl: "https://exchange.example/kyc-spa/token",
+ kycAmlReview: true,
+ },
+ exchange: null,
+ confirmation: { unavailableReasons: ["not-proposed"] },
+};
+const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
+function fixture() {
+ const notifications = new Set<(n: WalletNotification) => void>();
+ let statusListener: (s: ConnectionStatus) => void = () => {};
+ let ack!: () => void;
+ const acknowledgement = new Promise<void>((resolve) => (ack = resolve));
+ const calls: { op: string; id: string }[] = [];
+ const connection = {
+ client: {
+ async call(op: string, args: { observationId: string }) {
+ calls.push({ op, id: args.observationId });
+ if (op === WalletApiOperation.ObservePeerPushCredit)
+ await acknowledgement;
+ return {};
+ },
+ } as unknown as WalletConnection["client"],
+ subscribeNotifications(listener: (n: WalletNotification) => void) {
+ notifications.add(listener);
+ return () => {
+ notifications.delete(listener);
+ };
+ },
+ subscribeStatus(listener: (s: ConnectionStatus) => void) {
+ statusListener = listener;
+ listener({ state: "connected" });
+ return () => {
+ statusListener = () => {};
+ };
+ },
+ close() {},
+ } satisfies WalletConnection;
+ const emit = (n: WalletNotification) => {
+ for (const listener of notifications) listener(n);
+ };
+ const send = (
+ id: string,
+ revision: number,
+ value: PeerPushCreditSnapshot | null = snapshot,
+ ) =>
+ emit({
+ type: NotificationType.ObservationSnapshot,
+ observationType: ObservationType.PeerPushCredit,
+ transactionId,
+ observationId: id,
+ revision,
+ snapshot: value,
+ });
+ let serial = 0;
+ const observer = new PeerCreditObservation(
+ connection,
+ transactionId,
+ () => {},
+ () => `view-${++serial}`,
+ );
+ return {
+ observer,
+ calls,
+ send,
+ emit,
+ ack,
+ status: (s: ConnectionStatus) => statusListener(s),
+ notifications,
+ };
+}
+
+function readState(observer: PeerCreditObservation) {
+ return observer.state;
+}
+function failureMessage(observer: PeerCreditObservation) {
+ const state = observer.state;
+ return state.status === "failed" ? state.error.message : undefined;
+}
+
+function currentSnapshot(observer: PeerCreditObservation) {
+ const state = observer.state;
+ return state.status === "deleted" ? undefined : state.snapshot;
+}
+
+test("initial notification before acknowledgement, revision filtering and complete replacement", async () => {
+ const f = fixture();
+ f.send("other", 50);
+ assert.equal(currentSnapshot(f.observer), undefined);
+ f.send("view-1", 1);
+ assert.equal(currentSnapshot(f.observer), snapshot);
+ f.send("view-1", 1, null);
+ assert.equal(readState(f.observer).status === "deleted", false);
+ const replacement = {
+ ...snapshot,
+ transaction: {
+ ...snapshot.transaction,
+ kycUrl: undefined,
+ kycAmlReview: undefined,
+ },
+ };
+ f.send("view-1", 2, replacement);
+ assert.deepEqual(currentSnapshot(f.observer), replacement);
+ f.ack();
+ await tick();
+ assert.equal(currentSnapshot(f.observer), replacement);
+ f.observer.dispose();
+});
+
+test("dispose during registration stops again after acknowledgement and ignores late values", async () => {
+ const f = fixture();
+ f.observer.dispose();
+ f.send("view-1", 1);
+ f.ack();
+ await tick();
+ assert.equal(currentSnapshot(f.observer), undefined);
+ assert.equal(f.notifications.size, 0);
+ assert.equal(
+ f.calls.filter((c) => c.op === WalletApiOperation.StopObservation).length,
+ 2,
+ );
+});
+
+test("reconnect replaces registration; errors permit retry and deletion ends it", async () => {
+ const f = fixture();
+ f.send("view-1", 1);
+ f.status({ state: "disconnected", reason: "lost", unknownMutationIds: [] });
+ assert.equal(readState(f.observer).status, "disconnected");
+ assert.equal(currentSnapshot(f.observer), snapshot);
+ f.status({ state: "connected" });
+ assert.deepEqual(readState(f.observer), { status: "loading", snapshot });
+ f.send("view-1", 50, null);
+ assert.equal(readState(f.observer).status === "deleted", false);
+ f.send("view-2", 1);
+ assert.equal(readState(f.observer).status, "ready");
+ f.emit({
+ type: NotificationType.ObservationError,
+ observationType: ObservationType.PeerPushCredit,
+ observationId: "view-2",
+ error: { code: 1, hint: "read failed" },
+ });
+ assert.equal(failureMessage(f.observer), "read failed");
+ f.status({ state: "connected" });
+ assert.equal(
+ f.calls.filter((c) => c.op === WalletApiOperation.ObservePeerPushCredit)
+ .length,
+ 2,
+ );
+ f.observer.retry();
+ assert.deepEqual(readState(f.observer), { status: "loading", snapshot });
+ f.send("view-3", 1, null);
+ assert.equal(readState(f.observer).status, "deleted");
+ f.status({ state: "disconnected", reason: "lost", unknownMutationIds: [] });
+ f.status({ state: "connected" });
+ f.observer.retry();
+ assert.deepEqual(readState(f.observer), { status: "deleted" });
+ assert.equal(
+ f.calls.filter((c) => c.op === WalletApiOperation.ObservePeerPushCredit)
+ .length,
+ 3,
+ );
+ f.ack();
+ await tick();
+ f.observer.dispose();
+});
+
+test("extension disconnect cleans up registration that completes after disconnect", async () => {
+ let complete!: (r: CoreApiResponse) => void;
+ const calls: CoreApiRequestEnvelope[] = [];
+ const owner = new ObservationOwner(async (request) => {
+ calls.push(request);
+ if (request.operation === WalletApiOperation.ObservePeerPushCredit)
+ return new Promise((resolve) => (complete = resolve));
+ return {
+ type: "response",
+ id: request.id,
+ operation: request.operation,
+ result: {},
+ };
+ });
+ const request = {
+ operation: WalletApiOperation.ObservePeerPushCredit,
+ id: "register",
+ args: { observationId: "view", transactionId },
+ };
+ const result = owner.handle(request);
+ owner.close();
+ complete({
+ type: "response",
+ id: request.id,
+ operation: request.operation,
+ result: {},
+ });
+ await result;
+ assert.equal(
+ calls.filter((c) => c.operation === WalletApiOperation.StopObservation)
+ .length,
+ 1,
+ );
+});