taler-typescript-core

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

commit 18ad284d729260adeeb442232218fa7e9841bd70
parent b8575f51aca313f76318a3dfa4d870ec32c56bc9
Author: Florian Dold <dold@taler.net>
Date:   Mon, 23 Nov 2026 19:50:13 +0100

wallet web UI: add a Notifications screen and an unread badge

Diffstat:
Mpackages/taler-harness/src/integrationtests/test-wallet-web-ui-pwa-withdrawal.ts | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/src/api/observations.ts | 20++++++++++++++++++++
Mpackages/wallet-webui/src/routes/App.tsx | 14+++++++++++++-
Apackages/wallet-webui/src/routes/UserAttentionRoute.tsx | 233+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/src/testing/demo-wallet.ts | 37+++++++++++++++++++++++++++++++++----
Mpackages/wallet-webui/src/ui/Button.tsx | 2++
Mpackages/wallet-webui/src/ui/Shell.tsx | 28++++++++++++++++++++++++----
Mpackages/wallet-webui/test/observations-hook.test.tsx | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/test/screens.test.tsx | 10++++++++++
9 files changed, 476 insertions(+), 9 deletions(-)

diff --git a/packages/taler-harness/src/integrationtests/test-wallet-web-ui-pwa-withdrawal.ts b/packages/taler-harness/src/integrationtests/test-wallet-web-ui-pwa-withdrawal.ts @@ -1204,6 +1204,86 @@ async function runPwaWithdrawalTest( ); await stage.step( + "preview attention items alongside the refresh block", + async (page) => { + const apply = async (name: string) => { + await page.goto(`${pwaUrl}#/enter`); + const link = page.getByLabel("Wallet link"); + await link.fill("taler://dev-experiment/" + name); + await link.press("Enter"); + await page + .getByRole("button", { name: "Apply experiment" }) + .click(); + await page.getByText(/was applied/).waitFor(); + }; + await page.goto(`${pwaUrl}#/settings?section=refresh`); + await page + .getByRole("checkbox", { name: "Block coin refreshes" }) + .click(); + await apply("show-user-attention"); + await page.goto(`${pwaUrl}#/`); + const unreadBalances = page + .getByRole("navigation", { name: "Wallet", exact: true }) + .locator('a[aria-description="Unread notifications"]'); + await unreadBalances.waitFor(); + await page.getByRole("link", { name: /Notifications/ }).click(); + await page + .getByText("Test notification", { exact: true }) + .nth(3) + .waitFor(); + const spendingWarning = page.getByRole("heading", { + name: "Funds already spent", + }); + await spendingWarning.waitFor(); + await page + .getByText( + "Your wallet found that 5 KUDOS had already been spent.", + { exact: true }, + ) + .waitFor(); + const sample = page + .locator("section") + .filter({ hasText: "Test notification" }) + .filter({ + has: page.getByRole("heading", { + name: "Exchange terms have changed", + }), + }); + await sample.getByRole("button", { name: "Mark as read" }).click(); + await sample + .getByRole("button", { name: "Mark as read" }) + .waitFor({ state: "detached" }); + await page + .getByRole("button", { name: "Mark all as read" }) + .click(); + await unreadBalances.waitFor({ state: "detached" }); + await page + .getByText("Test notification", { exact: true }) + .nth(3) + .waitFor(); + await page.getByRole("button", { name: "Clear read" }).click(); + await spendingWarning.waitFor({ state: "detached" }); + await page + .getByText("Test notification", { exact: true }) + .nth(2) + .waitFor(); + await page + .getByRole("link", { name: "Open developer settings" }) + .waitFor(); + await apply("clear-user-attention"); + await page.goto(`${pwaUrl}#/notifications`); + await page + .getByRole("link", { name: "Open developer settings" }) + .click(); + const toggle = page.getByRole("checkbox", { + name: "Block coin refreshes", + checked: true, + }); + await toggle.click(); + }, + ); + + await stage.step( "clear the wallet from developer settings", async (page) => { await page.goto(`${pwaUrl}#/settings`); diff --git a/packages/wallet-webui/src/api/observations.ts b/packages/wallet-webui/src/api/observations.ts @@ -7,6 +7,7 @@ import { NotificationType, type TransactionSnapshot, + type UserAttentionSnapshot, type ObservationSnapshotNotification, type ScopeInfo, type WalletRefreshInfo, @@ -373,3 +374,22 @@ export function useBalanceRefreshInfo( retry, }; } + +export function useUserAttention(connection: WalletConnection) { + return useObservation<UserAttentionSnapshot>( + 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, + ), + ); +} diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx @@ -1,3 +1,4 @@ +import { HomeAttentionLink, UserAttentionRoute } from "./UserAttentionRoute.js"; import { usePaymentActions, type PaymentActions } from "./payment-actions.js"; import { peerCreditConfirmationView } from "./peer-credit-review-model.js"; import { @@ -456,6 +457,12 @@ function HostRecoveryNotice() { function WalletShell() { const { connection, demo } = useServices(); + const attention = useWalletQuery( + connection, + WalletApiOperation.GetUserAttentionSummary, + {}, + ); + const unreadCount = attention.data?.unreadCount ?? 0; const [, navigate] = useLocation(); const { mutate } = useSWRConfig(); const [demoNotice, setDemoNotice] = useState<string>(); @@ -477,6 +484,7 @@ function WalletShell() { return ( <Shell connectionLabel={label} + hasUnreadAttention={unreadCount > 0} demo={ demo ? { @@ -497,7 +505,11 @@ function WalletShell() { <HostRecoveryNotice /> <VisibleRequestProgress /> <Switch> - <Route path="/" component={BalanceRoute} /> + <Route path="/"> + <HomeAttentionLink unreadCount={unreadCount} /> + <BalanceRoute /> + </Route> + <Route path="/notifications" component={UserAttentionRoute} /> <Route path="/enter" component={UriInputRoute} /> <Route path="/action/:id" component={KeyedActionRoute} /> <Route diff --git a/packages/wallet-webui/src/routes/UserAttentionRoute.tsx b/packages/wallet-webui/src/routes/UserAttentionRoute.tsx @@ -0,0 +1,233 @@ +/* + * This file is part of GNU Taler + * (C) 2026 Taler Systems S.A. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +import { + Amounts, + TransactionType, + type UserAttentionItem, +} from "@gnu-taler/taler-util"; +import { + WalletApiOperation, + type WalletCoreRequestType, +} from "@gnu-taler/taler-wallet-core"; +import { useState } from "preact/hooks"; +import { useUserAttention } from "../api/observations.js"; +import { i18n } from "../i18n/runtime.js"; +import { Button } from "../ui/Button.js"; +import { Card } from "../ui/Card.js"; +import { useServices } from "./context.js"; +import { exchangeRouteId } from "./management-model.js"; + +export function HomeAttentionLink({ unreadCount }: { unreadCount: number }) { + return ( + <div class="mx-auto mb-3 flex max-w-6xl justify-end"> + <a + href="#/notifications" + class="inline-flex min-h-11 items-center gap-2 rounded-lg px-3 text-primary hover:bg-secondaryContainer" + > + {i18n.str`Notifications`} + {unreadCount > 0 && ( + <span class="rounded-full bg-primary px-2 text-onPrimary"> + {unreadCount} + </span> + )} + </a> + </div> + ); +} + +function title(item: UserAttentionItem) { + switch (item.type) { + case "coin-double-spent": + return i18n.str`Funds already spent`; + case "exchange-tos-changed": + return i18n.str`Exchange terms have changed`; + case "exchange-master-key-changed": + return i18n.str`Exchange master key has changed`; + case "exchange-currency-changed": + return i18n.str`Exchange identity changed`; + case "refresh-blocked-for-debugging": + return i18n.str`Coin refreshes are blocked`; + default: + return i18n.str`Wallet update`; + } +} + +function reviewLink(item: UserAttentionItem) { + if (item.isSample) return; + switch (item.type) { + case "coin-double-spent": { + if (!item.transactionId) return; + const url = "/transaction/" + item.transactionId; + if (item.transactionId.startsWith(`txn:${TransactionType.Refresh}:`)) + return { url, label: i18n.str`View affected refresh` }; + return { + url, + label: item.merchantName + ? i18n.str`View payment to ${item.merchantName}` + : i18n.str`View affected payment`, + }; + } + case "exchange-tos-changed": + return { + url: + "/exchange/" + + exchangeRouteId(item.exchangeBaseUrl) + + "/terms?returnTo=%2Fnotifications", + label: i18n.str`Review terms`, + }; + case "exchange-currency-changed": + case "exchange-master-key-changed": + return { + url: + "/exchange/" + + exchangeRouteId(item.exchangeBaseUrl) + + "?returnTo=%2Fnotifications", + label: + item.type === "exchange-currency-changed" + ? i18n.str`Review exchange` + : i18n.str`Review exchange keys`, + }; + case "refresh-blocked-for-debugging": + return { + url: "/settings?section=refresh", + label: i18n.str`Open developer settings`, + }; + } +} + +type InboxAction = + | WalletApiOperation.MarkUserAttentionRead + | WalletApiOperation.DismissUserAttention + | WalletApiOperation.MarkAllUserAttentionRead + | WalletApiOperation.ClearReadUserAttention; + +export function UserAttentionRoute() { + const { connection } = useServices(); + const { state, retry } = useUserAttention(connection); + const [error, setError] = useState<string>(); + const [updating, setUpdating] = useState(false); + const snapshot = "snapshot" in state ? state.snapshot : undefined; + const items = snapshot?.items; + const busy = state.status !== "ready" || updating; + async function update<Op extends InboxAction>( + op: Op, + args: WalletCoreRequestType<Op>, + ) { + try { + setUpdating(true); + setError(undefined); + await connection.client.call(op, args); + } catch (e) { + setError( + e instanceof Error + ? e.message + : i18n.str`Could not update the notification.`, + ); + } finally { + setUpdating(false); + } + } + return ( + <div class="mx-auto max-w-3xl space-y-4"> + <a href="#/" class="text-primary">{i18n.str`Back to wallet`}</a> + <div class="flex flex-wrap items-center justify-between gap-3"> + <h1 class="text-2xl font-bold">{i18n.str`Notifications`}</h1> + <div class="flex flex-wrap gap-2"> + <Button + tone="secondary" + disabled={busy || !snapshot?.unreadCount} + onClick={() => + void update(WalletApiOperation.MarkAllUserAttentionRead, {}) + } + >{i18n.str`Mark all as read`}</Button> + <Button + tone="secondary" + disabled={ + busy || !items?.some((item) => item.readAt && item.dismissible) + } + aria-description={i18n.str`Clear read notifications that can be dismissed.`} + onClick={() => + void update(WalletApiOperation.ClearReadUserAttention, {}) + } + >{i18n.str`Clear read`}</Button> + </div> + </div> + {state.status === "loading" && ( + <p role="status">{i18n.str`Loading notifications…`}</p> + )} + {state.status === "disconnected" && ( + <p role="status">{i18n.str`Waiting for the wallet to reconnect…`}</p> + )} + {state.status === "failed" && ( + <p role="alert"> + {state.error.message}{" "} + <Button onClick={retry}>{i18n.str`Retry`}</Button> + </p> + )} + {error && <p role="alert">{error}</p>} + {items?.length === 0 && <p>{i18n.str`No notifications.`}</p>} + {items?.map((item) => { + const link = reviewLink(item); + return ( + <Card key={item.attentionId}> + <div class="flex items-baseline justify-between gap-3"> + <h2 class="font-semibold">{title(item)}</h2> + {!item.readAt && ( + <span class="text-sm text-primary">{i18n.str`Unread`}</span> + )} + </div> + {item.isSample && ( + <p class="text-sm">{i18n.str`Test notification`}</p> + )} + {item.type === "coin-double-spent" && ( + <p>{ + /* Translators: The placeholders are the original debit value and its currency. */ + i18n.str`Your wallet found that ${Amounts.stringifyValue(item.amountSpentElsewhere)} ${Amounts.currencyOf(item.amountSpentElsewhere)} had already been spent.` + }</p> + )} + {"exchangeBaseUrl" in item && ( + <p class="break-all text-secondary">{item.exchangeBaseUrl}</p> + )} + {item.type === "exchange-currency-changed" && ( + <p> + {item.previousCurrency} → {item.currentCurrency} + </p> + )} + <div class="mt-3 flex flex-wrap items-center gap-3"> + {link && ( + <a class="text-primary underline" href={`#${link.url}`}> + {link.label} + </a> + )} + {!item.readAt && ( + <Button + tone="secondary" + disabled={busy} + onClick={() => + void update(WalletApiOperation.MarkUserAttentionRead, { + attentionId: item.attentionId, + }) + } + >{i18n.str`Mark as read`}</Button> + )} + {item.dismissible && ( + <Button + tone="secondary" + disabled={busy} + onClick={() => + void update(WalletApiOperation.DismissUserAttention, { + attentionId: item.attentionId, + }) + } + >{i18n.str`Dismiss`}</Button> + )} + </div> + </Card> + ); + })} + </div> + ); +} diff --git a/packages/wallet-webui/src/testing/demo-wallet.ts b/packages/wallet-webui/src/testing/demo-wallet.ts @@ -454,6 +454,7 @@ export class DemoWalletConnection implements WalletConnection { string, { scope: ScopeInfo; revision: number; value?: string } >(); + private attentionObservers = new Set<string>(); private observations = new Map< string, { transactionId: string; revision: number; value?: string } @@ -494,6 +495,15 @@ export class DemoWalletConnection implements WalletConnection { return `txn:${kind}:demo-${++this.state.sequence}` as TransactionIdStr; } + private requireUnusedObservationId(id: string): void { + if ( + this.observations.has(id) || + this.refreshObservers.has(id) || + this.attentionObservers.has(id) + ) + throw Error("Observation ID already active"); + } + private emit(notification: WalletNotification): void { for (const listener of this.notifications) listener(notification); if ( @@ -1248,12 +1258,31 @@ export class DemoWalletConnection implements WalletConnection { transactionId: id, } as never); } + case WalletApiOperation.GetUserAttentionSummary: + return { unreadCount: 0 } as never; + case WalletApiOperation.GetUserAttention: + return { items: [], unreadCount: 0 } as never; + case WalletApiOperation.MarkAllUserAttentionRead: + case WalletApiOperation.ClearReadUserAttention: + return {} as never; + case WalletApiOperation.ObserveUserAttention: { + const id = String(request.observationId); + this.requireUnusedObservationId(id); + this.attentionObservers.add(id); + this.emit({ + type: NotificationType.ObservationSnapshot, + observationType: ObservationType.UserAttention, + observationId: id, + revision: 1, + snapshot: { items: [], unreadCount: 0 }, + }); + return {} as never; + } case WalletApiOperation.GetBalanceRefreshInfo: return this.refreshInfo(request.scopeInfo as ScopeInfo) as never; case WalletApiOperation.ObserveBalanceRefreshInfo: { const id = String(request.observationId); - if (this.observations.has(id) || this.refreshObservers.has(id)) - throw Error("Observation ID already active"); + this.requireUnusedObservationId(id); this.refreshObservers.set(id, { scope: request.scopeInfo as ScopeInfo, revision: 0, @@ -1263,8 +1292,7 @@ export class DemoWalletConnection implements WalletConnection { } case WalletApiOperation.ObserveTransaction: { const id = String(request.observationId); - if (this.observations.has(id) || this.refreshObservers.has(id)) - throw Error("Observation ID already active"); + this.requireUnusedObservationId(id); const t = this.findTransaction(String(request.transactionId)); this.observations.set(id, { @@ -1275,6 +1303,7 @@ export class DemoWalletConnection implements WalletConnection { return {} as never; } case WalletApiOperation.StopObservation: + this.attentionObservers.delete(String(request.observationId)); this.refreshObservers.delete(String(request.observationId)); this.observations.delete(String(request.observationId)); return {} as never; diff --git a/packages/wallet-webui/src/ui/Button.tsx b/packages/wallet-webui/src/ui/Button.tsx @@ -5,6 +5,7 @@ export function Button(props: { onClick?: () => void; type?: "button" | "submit"; disabled?: boolean; + "aria-description"?: string; tone?: "primary" | "secondary" | "danger"; }) { const tone = props.tone ?? "primary"; @@ -18,6 +19,7 @@ export function Button(props: { <button type={props.type ?? "button"} disabled={props.disabled} + aria-description={props["aria-description"]} onClick={props.onClick} class={`min-h-11 rounded-full px-5 py-2 font-semibold transition focus:outline-none disabled:cursor-not-allowed disabled:bg-outlineVariant disabled:text-outline ${colors}`} > diff --git a/packages/wallet-webui/src/ui/Shell.tsx b/packages/wallet-webui/src/ui/Shell.tsx @@ -9,6 +9,7 @@ import type { DemoScenario, DemoScenarioId } from "../routes/context.js"; export function Shell(props: { children: ComponentChildren; connectionLabel: string; + hasUnreadAttention?: boolean; demo?: { scenarios: readonly DemoScenario[]; notice?: string; @@ -34,8 +35,20 @@ export function Shell(props: { // Translators: Navigation command to deposit wallet funds into a bank // account (cash out), not to add funds to the wallet. const depositLabel = i18n.ctx("wallet action")`Deposit`; - // Translators: Mobile navigation item for the wallet's currency balances. - const balancesLabel = i18n.str`Balances`; + const unreadDescription = props.hasUnreadAttention + ? i18n.str`Unread notifications` + : undefined; + const balancesLabel = ( + <span class="inline-flex items-center gap-1.5"> + {i18n.str`Balances`} + {props.hasUnreadAttention && ( + <span + aria-hidden="true" + class="h-2 w-2 shrink-0 rounded-full bg-error" + /> + )} + </span> + ); return ( <div class="min-h-screen bg-background pb-24 text-onBackground md:pb-0"> <header @@ -121,7 +134,10 @@ export function Shell(props: { href="/" icon="balances" selected={selected("/")} - >{i18n.str`Balances`}</ActionNav> + description={unreadDescription} + > + {balancesLabel} + </ActionNav> <ActionNav href="/transactions" icon="history" @@ -159,7 +175,7 @@ export function Shell(props: { aria-label={i18n.str`Wallet`} class="fixed inset-x-0 bottom-0 z-20 grid grid-cols-3 items-end border-t border-outlineVariant bg-surface px-4 pb-[max(.55rem,env(safe-area-inset-bottom))] pt-2 md:hidden" > - <MobileNav href="/" icon="balances"> + <MobileNav href="/" icon="balances" description={unreadDescription}> {balancesLabel} </MobileNav> <Link @@ -182,12 +198,14 @@ function ActionNav(props: { href: string; icon: WalletIconName; selected?: boolean; + description?: string; children: ComponentChildren; }) { return ( <Link href={props.href} aria-current={props.selected ? `page` : undefined} + aria-description={props.description} class={`flex items-center gap-3 rounded-xl px-3 py-2.5 font-medium ${props.selected ? "bg-primaryContainer text-onPrimaryContainer" : "hover:bg-secondaryContainer"}`} > <WalletIcon name={props.icon} class="h-5 w-5 shrink-0" /> @@ -199,11 +217,13 @@ function ActionNav(props: { function MobileNav(props: { href: string; icon: WalletIconName; + description?: string; children: ComponentChildren; }) { return ( <Link href={props.href} + aria-description={props.description} class="flex min-h-12 flex-col items-center justify-end gap-0.5 text-xs font-medium text-secondary" > <WalletIcon name={props.icon} class="h-6 w-6 text-onSurface" /> diff --git a/packages/wallet-webui/test/observations-hook.test.tsx b/packages/wallet-webui/test/observations-hook.test.tsx @@ -22,11 +22,14 @@ import { usePaymentContract, type PaymentContractView, } from "../src/api/observations.js"; +import { ServicesContext } from "../src/routes/context.js"; +import { UserAttentionRoute } from "../src/routes/UserAttentionRoute.js"; import type { WalletConnection, ConnectionStatus, } from "../src/api/contracts.js"; import { + createDemoServices, DemoWalletConnection, demoActionUris, } from "../src/testing/demo-wallet.js"; @@ -485,3 +488,61 @@ test("a failed balance observation keeps the last warning and retries with a fre await dom.happyDOM.abort(); } }); + +test("spending warnings link to the affected merchant payment, peer payment, or refresh", async () => { + const dom = installDom(); + const { render, cleanup } = await import("@testing-library/preact"); + const services = createDemoServices(); + const examples = [ + { + id: "txn:payment:merchant", + merchantName: "Example Shop", + label: "View payment to Example Shop", + }, + { id: "txn:peer-push-debit:purse", label: "View affected payment" }, + { id: "txn:refresh:group", label: "View affected refresh" }, + ]; + const connection = services.connection; + const subscribe = connection.subscribeNotifications.bind(connection); + connection.subscribeNotifications = (listener) => + subscribe((n) => { + if ( + n.type !== NotificationType.ObservationSnapshot || + n.observationType !== ObservationType.UserAttention + ) + return listener(n); + listener({ + ...n, + snapshot: { + unreadCount: examples.length, + items: examples.map((example) => ({ + type: "coin-double-spent", + attentionId: example.id, + createdAt: { t_s: 1 }, + transactionId: example.id as TransactionIdStr, + merchantName: example.merchantName, + amountSpentElsewhere: "KUDOS:5", + exchangeBaseUrls: ["https://exchange.example/"], + dismissible: true, + })), + }, + }); + }); + try { + const view = render( + <ServicesContext.Provider value={services}> + <UserAttentionRoute /> + </ServicesContext.Provider>, + ); + for (const { label, id } of examples) { + assert.equal( + (await view.findByRole("link", { name: label })).getAttribute("href"), + "#/transaction/" + id, + ); + } + } finally { + cleanup(); + connection.close(); + await dom.happyDOM.abort(); + } +}); diff --git a/packages/wallet-webui/test/screens.test.tsx b/packages/wallet-webui/test/screens.test.tsx @@ -491,6 +491,16 @@ test("DD 86 desktop shell exposes every supported navigation entry", async () => .getAttribute("href"), "/", ); + view.rerender( + <Shell connectionLabel="Connected" hasUnreadAttention> + <p>Wallet content</p> + </Shell>, + ); + for (const link of view.getAllByRole("link", { + name: "Balances", + exact: true, + })) + assert.equal(link.getAttribute("aria-description"), "Unread notifications"); cleanup(); await window.happyDOM.abort(); });