commit a3d238ae00b02d1ce6250f80aa90c0cac7ddcc89
parent 7d61b4bf4f97611ce03f6323fd5b2dc7a870ae8b
Author: Florian Dold <dold@taler.net>
Date: Wed, 25 Nov 2026 18:52:56 +0100
wallet web UI: use leased watches in the observation hooks
Transaction, balance refresh and inbox views now share one client.
Recheck leases when the page becomes visible and wait for a fresh
balance snapshot before offering to dismiss a renewal warning.
Issue: https://bugs.taler.net/n/11794
Diffstat:
4 files changed, 41 insertions(+), 183 deletions(-)
diff --git a/packages/wallet-webui/src/api/observations.ts b/packages/wallet-webui/src/api/observations.ts
@@ -5,10 +5,8 @@
*/
import {
- NotificationType,
type TransactionSnapshot,
type UserAttentionSnapshot,
- type ObservationSnapshotNotification,
type ScopeInfo,
type WalletRefreshInfo,
stringifyScopeInfo,
@@ -17,157 +15,18 @@ import {
type MerchantContractTerms,
type TransactionIdStr,
} from "@gnu-taler/taler-util";
-import { WalletApiOperation } from "@gnu-taler/taler-wallet-core";
+import {
+ createWalletObservationClient,
+ type ObservationHandle,
+ type ObservationState,
+ 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";
-type ObservationState<T> =
- | { status: "loading"; snapshot?: T }
- | { status: "ready"; snapshot: T }
- | { status: "disconnected"; snapshot?: T }
- | { status: "failed"; error: Error; snapshot?: T }
- | { status: "deleted" };
-
-/** Owns one UI subscription; registration acknowledgements never carry state. */
-class WalletObservation<T> {
- state: ObservationState<T> = { 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 register: (id: string) => Promise<unknown>,
- select: (n: ObservationSnapshotNotification) => T | null | undefined,
- fallbackError: string,
- private changed: (state: ObservationState<T>) => 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) {
- if (n.revision <= this.revision) return;
- const snapshot = select(n);
- if (snapshot === undefined) return;
- this.revision = n.revision;
- if (snapshot === null) this.id = undefined;
- this.update(
- snapshot === null
- ? { status: "deleted" }
- : { status: "ready", snapshot },
- );
- } 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 ?? fallbackError),
- });
- }
- });
- 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: ObservationState<T>) {
- 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.register(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 type TransactionObservationState = ObservationState<TransactionSnapshot>;
-export class TransactionObservation extends WalletObservation<TransactionSnapshot> {
- constructor(
- connection: WalletConnection,
- transactionId: TransactionIdStr,
- changed: (state: TransactionObservationState) => void,
- newId?: () => string,
- ) {
- super(
- connection,
- (observationId) =>
- connection.client.call(WalletApiOperation.ObserveTransaction, {
- transactionId,
- observationId,
- }),
- (n) =>
- n.observationType === "transaction" && n.transactionId === transactionId
- ? n.snapshot
- : undefined,
- i18n.str`Transaction updates stopped.`,
- changed,
- newId,
- );
- }
-}
-
export interface TransactionObservationView {
state: TransactionObservationState;
snapshot?: TransactionSnapshot;
@@ -186,7 +45,10 @@ export function useTransactionObservation(
connection,
transactionId,
(changed) =>
- new TransactionObservation(connection, transactionId!, changed),
+ createWalletObservationClient(connection).watchTransaction(
+ transactionId!,
+ changed,
+ ),
);
const snapshot = "snapshot" in state ? state.snapshot : undefined;
const error =
@@ -317,16 +179,14 @@ export function usePaymentContract(
function useObservation<T>(
connection: WalletConnection,
key: string | undefined,
- create: (
- changed: (state: ObservationState<T>) => void,
- ) => WalletObservation<T>,
+ create: (changed: (state: ObservationState<T>) => void) => ObservationHandle,
) {
const [value, setValue] = useState<{
connection: WalletConnection;
key: string;
state: ObservationState<T>;
}>();
- const controller = useRef<WalletObservation<T>>();
+ const controller = useRef<ObservationHandle>();
useEffect(() => {
if (!key) return;
const instance = create((state) => setValue({ connection, key, state }));
@@ -352,23 +212,13 @@ export function useBalanceRefreshInfo(
connection,
key,
(changed) =>
- new WalletObservation(
- connection,
- (observationId) =>
- connection.client.call(WalletApiOperation.ObserveBalanceRefreshInfo, {
- observationId,
- scopeInfo: scope!,
- }),
- (n) =>
- n.observationType === "balance-refresh-info" &&
- stringifyScopeInfo(n.scopeInfo) === key
- ? n.snapshot
- : undefined,
- i18n.str`Balances could not be loaded.`,
+ createWalletObservationClient(connection).watchBalanceRefreshInfo(
+ scope!,
changed,
),
);
return {
+ ready: state.status === "ready",
snapshot: "snapshot" in state ? state.snapshot : undefined,
error: state.status === "failed" ? state.error : undefined,
retry,
@@ -380,16 +230,6 @@ export function useUserAttention(connection: WalletConnection) {
connection,
"user-attention",
(changed) =>
- new WalletObservation(
- connection,
- (observationId) =>
- connection.client.call(WalletApiOperation.ObserveUserAttention, {
- observationId,
- }),
- (n) =>
- n.observationType === "user-attention" ? n.snapshot : undefined,
- i18n.str`Notifications could not be loaded.`,
- changed,
- ),
+ createWalletObservationClient(connection).watchUserAttention(changed),
);
}
diff --git a/packages/wallet-webui/src/api/rpc.ts b/packages/wallet-webui/src/api/rpc.ts
@@ -218,6 +218,19 @@ export class RpcWalletConnection implements WalletConnection {
});
}
+ subscribeResume(listener: () => void): () => void {
+ if (typeof document === "undefined") return () => {};
+ const resume = () => {
+ if (document.visibilityState === "visible") listener();
+ };
+ document.addEventListener("visibilitychange", resume);
+ window.addEventListener("pageshow", resume);
+ return () => {
+ document.removeEventListener("visibilitychange", resume);
+ window.removeEventListener("pageshow", resume);
+ };
+ }
+
subscribeNotifications(
listener: (n: WalletNotification) => void,
): () => void {
diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx
@@ -835,13 +835,17 @@ function BalanceRoute() {
<BalanceScreen
renewalError={report.error}
onRetryRenewal={report.retry}
- onDismissRenewal={(warningId) => {
- void callMutation(
- WalletApiOperation.DismissWalletWarning,
- { warningId },
- [],
- );
- }}
+ onDismissRenewal={
+ report.ready
+ ? (warningId) => {
+ void callMutation(
+ WalletApiOperation.DismissWalletWarning,
+ { warningId },
+ [],
+ );
+ }
+ : undefined
+ }
balances={displayedBalances}
selectedScopeId={selectedBalance?.scopeId}
trend={balanceTrendView(
diff --git a/packages/wallet-webui/test/observations-hook.test.tsx b/packages/wallet-webui/test/observations-hook.test.tsx
@@ -408,6 +408,7 @@ test("the balance screen observes only its selected scope and updates dismissed
await view.findByText("none");
view.unmount();
assert.deepEqual(calls, [
+ WalletApiOperation.RenewObservations,
WalletApiOperation.ObserveBalanceRefreshInfo,
WalletApiOperation.DismissWalletWarning,
WalletApiOperation.StopObservation,