taler-typescript-core

Wallet core logic and WebUIs for various components
Log | Files | Refs | Submodules | README | LICENSE

commit 9ae302804d0c43d29dde42bc84a659628ec91211
parent d31664e48365ae144313e2bc583ef700ad8e0238
Author: Florian Dold <dold@taler.net>
Date:   Fri, 27 Nov 2026 02:18:14 +0100

wallet web UI: report connectivity from the wallet host

A wallet page can close or lose its connection while offline. Let the
host observe network changes for the lifetime of the wallet so pending
operations resume when connectivity returns.

Issue: https://bugs.taler.net/n/9691

Diffstat:
Mpackages/taler-harness/src/integrationtests/test-wallet-web-ui-pwa-lifecycle.ts | 43+++++++++++++------------------------------
Apackages/wallet-webui/src/platform/browser-network.ts | 41+++++++++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/src/platform/lifecycle.ts | 25-------------------------
Mpackages/wallet-webui/src/platform/wallet-host.ts | 7+++++++
Mpackages/wallet-webui/test/lifecycle.test.ts | 132++++++++++++++++++++++++++++++++++++++++---------------------------------------
5 files changed, 128 insertions(+), 120 deletions(-)

diff --git a/packages/taler-harness/src/integrationtests/test-wallet-web-ui-pwa-lifecycle.ts b/packages/taler-harness/src/integrationtests/test-wallet-web-ui-pwa-lifecycle.ts @@ -37,7 +37,7 @@ export async function runWalletWebUiPwaLifecycleTest(t: GlobalTestState) { await stage.page.addInitScript(() => { const browserGlobal = globalThis as any; const NativeWorker = browserGlobal.Worker; - const requests: Array<{ operation?: string; args?: unknown }> = []; + const requests: string[] = []; browserGlobal.__walletLifecycleRequests = requests; browserGlobal.__walletInjectMutationDisconnect = false; browserGlobal.Worker = new Proxy(NativeWorker, { @@ -46,10 +46,7 @@ export async function runWalletWebUiPwaLifecycleTest(t: GlobalTestState) { const nativePostMessage = worker.postMessage.bind(worker); worker.postMessage = (message: any, transfer?: unknown[]) => { if (message?.kind === "request") { - requests.push({ - operation: message.request?.operation, - args: message.request?.args, - }); + requests.push(message.request.operation); } if (transfer === undefined) nativePostMessage(message); else nativePostMessage(message, transfer); @@ -76,35 +73,21 @@ export async function runWalletWebUiPwaLifecycleTest(t: GlobalTestState) { await stage.run(async () => { await stage.step( - "hint initial and changed network availability", + "leave network availability hints to the wallet host", async (page) => { await page.goto(pwaUrl); await page .getByRole("heading", { name: /Balances|Welcome to Taler Wallet!/ }) .waitFor(); - await page.waitForFunction(() => - (globalThis as any).__walletLifecycleRequests.some( - (request: any) => - request.operation === "hintNetworkAvailability" && - request.args?.isNetworkAvailable === true, - ), - ); await page.context().setOffline(true); - await page.waitForFunction(() => - (globalThis as any).__walletLifecycleRequests.some( - (request: any) => - request.operation === "hintNetworkAvailability" && - request.args?.isNetworkAvailable === false, - ), - ); await page.context().setOffline(false); - await page.waitForFunction( - () => - (globalThis as any).__walletLifecycleRequests.filter( - (request: any) => - request.operation === "hintNetworkAvailability" && - request.args?.isNetworkAvailable === true, - ).length >= 2, + t.assertDeepEqual( + await page.evaluate(() => + (globalThis as any).__walletLifecycleRequests.includes( + "hintNetworkAvailability", + ), + ), + false, ); }, ); @@ -130,8 +113,8 @@ export async function runWalletWebUiPwaLifecycleTest(t: GlobalTestState) { ); }); await page.waitForFunction(() => - (globalThis as any).__walletLifecycleRequests.some( - (request: any) => request.operation === "hintApplicationResumed", + (globalThis as any).__walletLifecycleRequests.includes( + "hintApplicationResumed", ), ); }, @@ -162,7 +145,7 @@ export async function runWalletWebUiPwaLifecycleTest(t: GlobalTestState) { const attempts = await page.evaluate( () => (globalThis as any).__walletLifecycleRequests.filter( - (request: any) => request.operation === "addExchange", + (operation: string) => operation === "addExchange", ).length, ); t.assertDeepEqual(attempts, 1); diff --git a/packages/wallet-webui/src/platform/browser-network.ts b/packages/wallet-webui/src/platform/browser-network.ts @@ -0,0 +1,41 @@ +/* + * This file is part of GNU Taler + * (C) 2026 Taler Systems S.A. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +interface BrowserNetworkScope extends EventTarget { + navigator: { onLine: boolean; connection?: EventTarget }; + document?: Document; +} + +/** Each observer samples its own browser context, including on startup. */ +export function watchBrowserNetwork( + report: (online: boolean) => void, + scope: BrowserNetworkScope = globalThis, +): () => void { + const { navigator, document } = scope; + let lastOnline: boolean | undefined; + const update = () => { + const online = navigator.onLine; + if (online !== lastOnline) { + lastOnline = online; + report(online); + } + }; + scope.addEventListener("online", update); + scope.addEventListener("offline", update); + document?.addEventListener("visibilitychange", update); + // Chromium workers expose network information changes but don't dispatch + // online/offline events. Resample while running in case a change is missed. + navigator.connection?.addEventListener("change", update); + const timer = "ononline" in scope ? undefined : setInterval(update, 30_000); + update(); + return () => { + clearInterval(timer); + navigator.connection?.removeEventListener("change", update); + document?.removeEventListener("visibilitychange", update); + scope.removeEventListener("online", update); + scope.removeEventListener("offline", update); + }; +} diff --git a/packages/wallet-webui/src/platform/lifecycle.ts b/packages/wallet-webui/src/platform/lifecycle.ts @@ -8,9 +8,7 @@ export interface LifecycleEventSource { } export interface BrowserLifecycleEnvironment { - networkEvents: LifecycleEventSource; visibilityEvents: LifecycleEventSource; - isOnline(): boolean; visibilityState(): "hidden" | "visible"; observePower?: (report: (power: WalletPowerSource) => void) => () => void; } @@ -101,43 +99,25 @@ function observeBrowserPower( function defaultEnvironment(): BrowserLifecycleEnvironment { return { observePower: observeBrowserPower, - networkEvents: window, visibilityEvents: document, - isOnline: () => navigator.onLine, visibilityState: () => document.visibilityState === "hidden" ? "hidden" : "visible", }; } -/** - * Reconcile browser lifecycle events with wallet-core's task scheduler. - * Hints are advisory and never replay a business mutation. - */ export function watchWalletLifecycle( connection: WalletConnection, onResume: (healthy: boolean) => void, environment: BrowserLifecycleEnvironment = defaultEnvironment(), ): () => void { let stopped = false; - let lastOnline: boolean | undefined; const stopPower = environment.observePower?.((powerSource) => { void connection.client .call(WalletApiOperation.HintPowerState, { powerSource }) .catch(() => undefined); }); - const hintNetwork = () => { - const isNetworkAvailable = environment.isOnline(); - if (lastOnline === isNetworkAvailable) return; - lastOnline = isNetworkAvailable; - void connection.client - .call(WalletApiOperation.HintNetworkAvailability, { - isNetworkAvailable, - }) - .catch(() => undefined); - }; const resume = () => { if (environment.visibilityState() !== "visible") return; - hintNetwork(); void connection.client .call(WalletApiOperation.HintApplicationResumed, {}) .then((health) => { @@ -145,15 +125,10 @@ export function watchWalletLifecycle( }) .catch(() => undefined); }; - environment.networkEvents.addEventListener("online", hintNetwork); - environment.networkEvents.addEventListener("offline", hintNetwork); environment.visibilityEvents.addEventListener("visibilitychange", resume); - hintNetwork(); return () => { stopPower?.(); stopped = true; - environment.networkEvents.removeEventListener("online", hintNetwork); - environment.networkEvents.removeEventListener("offline", hintNetwork); environment.visibilityEvents.removeEventListener( "visibilitychange", resume, diff --git a/packages/wallet-webui/src/platform/wallet-host.ts b/packages/wallet-webui/src/platform/wallet-host.ts @@ -13,6 +13,7 @@ import { type WalletDbHandle, } from "@gnu-taler/taler-wallet-core"; import { isWalletDatabase, openBrowserIndexedDb } from "./storage-recovery.js"; +import { watchBrowserNetwork } from "./browser-network.js"; import { BrowserHttpLibrary } from "./browser-http.js"; import { BACKUP_OPERATION } from "../api/backup.js"; @@ -88,6 +89,11 @@ export async function startWalletHost( request.id, request.args, ); + const stopNetwork = watchBrowserNetwork((isNetworkAvailable) => { + void initializedWallet.client + .call(WalletApiOperation.HintNetworkAvailability, { isNetworkAvailable }) + .catch((error) => console.warn("Wallet network hint failed", error)); + }); const router = new ObservationRouter(dispatch); const backups = new BrowserBackupFiles(dispatch); const unsubscribe = initializedWallet.addNotificationListener((n) => { @@ -110,6 +116,7 @@ export async function startWalletHost( async stop() { if (!stopped) { stopped = true; + stopNetwork(); unsubscribe(); } await initializedWallet.shutdown(); diff --git a/packages/wallet-webui/test/lifecycle.test.ts b/packages/wallet-webui/test/lifecycle.test.ts @@ -5,10 +5,10 @@ import type { ConnectionStatus, WalletConnection, } from "../src/api/contracts.js"; +import { watchBrowserNetwork } from "../src/platform/browser-network.js"; import { watchWalletLifecycle, watchWalletReconnection, - type BrowserLifecycleEnvironment, type LifecycleEventSource, } from "../src/platform/lifecycle.js"; @@ -69,80 +69,84 @@ class FakeEvents implements LifecycleEventSource { } } -test("browser lifecycle hints network changes and revalidates after resume", async () => { - const networkEvents = new FakeEvents(); - const visibilityEvents = new FakeEvents(); - let online = true; - let visibility: "hidden" | "visible" = "visible"; - const calls: Array<{ operation: string; request: unknown }> = []; +test("stopping a UI observer leaves the host observing network changes", () => { + const connection = new EventTarget(); + const navigator = { onLine: false, connection }; + const scope = Object.assign(new EventTarget(), { navigator }); + const host: boolean[] = []; + const ui: boolean[] = []; + const stopHost = watchBrowserNetwork((online) => host.push(online), scope); + const closePopup = watchBrowserNetwork((online) => ui.push(online), scope); + closePopup(); + + navigator.onLine = true; + connection.dispatchEvent(new Event("change")); + scope.dispatchEvent(new Event("online")); + assert.deepEqual(host, [false, true]); + assert.deepEqual(ui, [false]); + + stopHost(); + navigator.onLine = false; + scope.dispatchEvent(new Event("offline")); + connection.dispatchEvent(new Event("change")); + assert.deepEqual(host, [false, true]); + const stopReplacement = watchBrowserNetwork( + (online) => host.push(online), + scope, + ); + assert.deepEqual(host, [false, true, false]); + stopReplacement(); +}); + +test("a worker resamples connectivity if the browser omits a network event", (t) => { + t.mock.timers.enable({ apis: ["setInterval"] }); + const navigator = { onLine: true }; + const scope = Object.assign(new EventTarget(), { navigator }); + const states: boolean[] = []; + const stop = watchBrowserNetwork((online) => states.push(online), scope); + navigator.onLine = false; + scope.dispatchEvent(new Event("offline")); + assert.deepEqual(states, [true, false]); + + navigator.onLine = true; + t.mock.timers.tick(30_000); + assert.deepEqual(states, [true, false, true]); + stop(); + navigator.onLine = false; + t.mock.timers.tick(30_000); + assert.deepEqual(states, [true, false, true]); +}); + +test("browser lifecycle revalidates when the document becomes visible", async () => { + const events = new FakeEvents(); + let visibility: "visible" | "hidden" = "hidden"; + const calls: string[] = []; const connection = { client: { - async call(operation: string, request: unknown) { - calls.push({ operation, request }); - if (operation === WalletApiOperation.HintApplicationResumed) { - return { dbReadHealthy: true, dbWriteHealthy: true }; - } - return {}; + async call(operation: string) { + calls.push(operation); + return { dbReadHealthy: true, dbWriteHealthy: true }; }, }, - } as WalletConnection; - const environment: BrowserLifecycleEnvironment = { - networkEvents, - visibilityEvents, - isOnline: () => online, - visibilityState: () => visibility, - }; - let resumes = 0; + } as unknown as WalletConnection; + const resumes: boolean[] = []; const stop = watchWalletLifecycle( connection, - (healthy) => { - if (healthy) resumes++; - }, - environment, - ); - - assert.deepEqual(calls, [ + (healthy) => resumes.push(healthy), { - operation: WalletApiOperation.HintNetworkAvailability, - request: { isNetworkAvailable: true }, + visibilityEvents: events, + visibilityState: () => visibility, }, - ]); - online = false; - networkEvents.emit("offline"); - networkEvents.emit("offline"); - visibility = "hidden"; - visibilityEvents.emit("visibilitychange"); - assert.equal( - calls.filter( - (call) => call.operation === WalletApiOperation.HintApplicationResumed, - ).length, - 0, ); + events.emit("visibilitychange"); + assert.deepEqual(calls, []); visibility = "visible"; - visibilityEvents.emit("visibilitychange"); - await Promise.resolve(); + events.emit("visibilitychange"); await Promise.resolve(); - assert.equal(resumes, 1); - assert.deepEqual( - calls.filter( - (call) => call.operation === WalletApiOperation.HintNetworkAvailability, - ), - [ - { - operation: WalletApiOperation.HintNetworkAvailability, - request: { isNetworkAvailable: true }, - }, - { - operation: WalletApiOperation.HintNetworkAvailability, - request: { isNetworkAvailable: false }, - }, - ], - ); - + assert.deepEqual(resumes, [true]); stop(); - online = true; - networkEvents.emit("online"); - assert.equal(calls.length, 3); + events.emit("visibilitychange"); + assert.deepEqual(calls, [WalletApiOperation.HintApplicationResumed]); }); test("power hints are reported and stopped with the browser lifecycle", async () => { @@ -162,9 +166,7 @@ test("power hints are reported and stopped with the browser lifecycle", async () }, } as WalletConnection; const stop = watchWalletLifecycle(connection, () => {}, { - networkEvents: events, visibilityEvents: events, - isOnline: () => true, visibilityState: () => "visible", observePower: (r) => { report = r;