taler-typescript-core

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

commit 62666d1ce7dd5415ec10d6dbf9ab4b2163e951a3
parent 1f60c9e78d6363756265a8b7c007e4b5e8c31b18
Author: Florian Dold <dold@taler.net>
Date:   Mon, 23 Nov 2026 19:48:40 +0100

wallet-core: add the notification inbox API

Clients can watch the inbox for changes or just fetch the unread count
for a badge.

Diffstat:
Mdoc/wallet-observations.md | 27+++++++++++++++++++++++++++
Mpackages/taler-util/src/notifications.ts | 11++++++++++-
Mpackages/taler-util/src/types-taler-wallet-observations.ts | 11+++++++++++
Mpackages/taler-wallet-core/src/db/shared.ts | 5+++++
Mpackages/taler-wallet-core/src/observations.ts | 21++++++++++++++++++++-
Mpackages/taler-wallet-core/src/requests.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apackages/taler-wallet-core/src/user-attention.ts | 162+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/src/wallet-api-types.ts | 73++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mpackages/taler-wallet-core/src/wallet-notifications.test.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-wallet-core/src/wallet.ts | 3+++
Mpackages/wallet-webui/src/api/notifications.ts | 7+++++++
Mpackages/wallet-webui/src/platform/observation-owner.ts | 1+
Mpackages/wallet-webui/test/notifications.test.ts | 8++++++++
13 files changed, 469 insertions(+), 3 deletions(-)

diff --git a/doc/wallet-observations.md b/doc/wallet-observations.md @@ -159,3 +159,30 @@ have been removed. Consumers must call `observeTransaction`, accept `observationType: "transaction"`, and narrow `snapshot.type`. `stopObservation` and lifecycle rules are unchanged. Transaction lists and balances retain their existing query/notification behavior. + +## User attention + +The web wallet labels the inbox **Notifications**. A home screen can subscribe to +the wallet-core `user-attention-changed` event and call +`getUserAttentionSummary({})` to get `{ unreadCount }`. Read the summary on +initial connection, reconnection and after each event. The event also fires +when an item reaches its expiry while the wallet is running. Attention changes +are independent of balance changes. + +An inbox can call `getUserAttention({})` for a single snapshot, or +`observeUserAttention({ observationId })` to receive snapshots with +`observationType: "user-attention"`. The snapshot contains `items` in +newest-first order and their `unreadCount`. Register and stop the observation +using the same lifecycle as a transaction view. + +Each item has a stable `attentionId` for that occurrence. Call +`markUserAttentionRead({ attentionId })` to set its `readAt` timestamp. Show +a dismiss action when `dismissible` is true and call +`dismissUserAttention({ attentionId })`. An item with `expiresAt` leaves the +inbox at that time. + +`markAllUserAttentionRead({})` marks every active unread occurrence as read. +`clearReadUserAttention({})` dismisses every active occurrence that is both +read and dismissible. Read condition-based warnings stay visible until their +conditions resolve. Each operation returns `{}` and emits one +`user-attention-changed` event when it changes the inbox. diff --git a/packages/taler-util/src/notifications.ts b/packages/taler-util/src/notifications.ts @@ -40,6 +40,7 @@ import type { } from "./types-taler-wallet-observations.js"; export enum NotificationType { + UserAttentionChanged = "user-attention-changed", ObservationSnapshot = "observation-snapshot", ObservationError = "observation-error", CoinRecoveryProgress = "coin-recovery-progress", @@ -88,7 +89,14 @@ export interface BalanceRefreshSnapshotNotification { } export type ObservationSnapshotNotification = | TransactionSnapshotNotification - | BalanceRefreshSnapshotNotification; + | BalanceRefreshSnapshotNotification + | { + type: NotificationType.ObservationSnapshot; + observationType: ObservationType.UserAttention; + observationId: string; + revision: number; + snapshot: import("./user-attention.js").UserAttentionSnapshot; + }; /** Ends the observation; does not describe the outcome of the transaction. */ export interface ObservationErrorNotification { @@ -480,6 +488,7 @@ export interface CoinRecoveryProgressNotification { } export type WalletNotification = + | { type: NotificationType.UserAttentionChanged } | ObservationSnapshotNotification | ObservationErrorNotification | CoinRecoveryProgressNotification diff --git a/packages/taler-util/src/types-taler-wallet-observations.ts b/packages/taler-util/src/types-taler-wallet-observations.ts @@ -46,6 +46,7 @@ import type { } from "./types-taler-wallet-transactions.js"; export enum ObservationType { + UserAttention = "user-attention", Transaction = "transaction", BalanceRefreshInfo = "balance-refresh-info", } @@ -72,6 +73,16 @@ export const codecForObserveBalanceRefreshInfoRequest = () => .property("observationId", codecForString()) .build("ObserveBalanceRefreshInfoRequest"); +export interface ObserveUserAttentionRequest { + /** Fresh caller-generated ID, unique within this wallet instance. */ + observationId: string; +} + +export const codecForObserveUserAttentionRequest = () => + buildCodecForObject<ObserveUserAttentionRequest>() + .property("observationId", codecForString()) + .build("ObserveUserAttentionRequest"); + export interface StopObservationRequest { observationId: string; } diff --git a/packages/taler-wallet-core/src/db/shared.ts b/packages/taler-wallet-core/src/db/shared.ts @@ -52,7 +52,12 @@ export function coalesceWalletNotifications( ): WalletNotification[] { const result: WalletNotification[] = []; const balances = new Map<string | undefined, BalanceChangeNotification>(); + let attentionChanged = false; for (const notification of notifications) { + if (notification.type === NotificationType.UserAttentionChanged) { + if (attentionChanged) continue; + attentionChanged = true; + } if (notification.type !== NotificationType.BalanceChange) { result.push(notification); continue; diff --git a/packages/taler-wallet-core/src/observations.ts b/packages/taler-wallet-core/src/observations.ts @@ -15,6 +15,7 @@ import { ObservationSnapshotNotification, ScopeInfo, WalletRefreshInfo, + UserAttentionSnapshot, TransactionSnapshot, TalerError, TalerErrorCode, @@ -96,6 +97,23 @@ export class WalletObservations { ); } + async registerUserAttention( + observationId: string, + read: () => Promise<UserAttentionSnapshot>, + ) { + await this.register( + observationId, + ObservationType.UserAttention, + async () => ({ + type: NotificationType.ObservationSnapshot, + observationType: ObservationType.UserAttention, + observationId, + revision: 0, + snapshot: await read(), + }), + ); + } + async registerRefreshInfo( observationId: string, scopeInfo: ScopeInfo, @@ -171,8 +189,9 @@ export class WalletObservations { } } - invalidate(): void { + invalidate(type?: ObservationType): void { for (const entry of this.entries.values()) { + if (type !== undefined && entry.observationType !== type) continue; entry.dirty = true; this.schedule(entry); } diff --git a/packages/taler-wallet-core/src/requests.ts b/packages/taler-wallet-core/src/requests.ts @@ -29,8 +29,18 @@ import { getBalanceRefreshInfo, observeBalanceRefreshInfo, } from "./refreshBalance.js"; +import { + scheduleAttentionExpirations, + getUserAttention, + markAllUserAttentionRead, + clearReadUserAttention, + updateAttention, +} from "./user-attention.js"; import { observeTransaction, stopObservation } from "./observe-transaction.js"; import { + AbsoluteTime, + codecForString, + buildCodecForObject, AbortTransactionRequest, AcceptBankIntegratedWithdrawalRequest, AcceptManualWithdrawalRequest, @@ -247,6 +257,7 @@ import { codecForObserveTransactionRequest, codecForBalanceRefreshInfoRequest, codecForObserveBalanceRefreshInfoRequest, + codecForObserveUserAttentionRequest, codecForStopObservationRequest, codecForPreparePeerPushCreditRequest, codecForPrepareRefundRequest, @@ -1024,6 +1035,10 @@ export async function handleCompleteExchangeBaseUrl( ); } +const attentionIdCodec = buildCodecForObject<{ attentionId: string }>() + .property("attentionId", codecForString()) + .build("UserAttentionById"); + async function handleSetWalletRunConfig( wex: WalletExecutionContext, req: InitRequest, @@ -1077,6 +1092,7 @@ async function handleSetWalletRunConfig( await migrateCoinAvailability(wex); if (!wex.ws.initCalled) { + await wex.runWalletDbTx((tx) => scheduleAttentionExpirations(wex, tx)); await repairLegacyRecoupState(wex); await cleanupFailedClaimsOnStartup(wex); await collectLeftoverClaims(wex); @@ -2073,6 +2089,8 @@ async function importDbDump( // raw IndexedDB handle, so none of the automatic invalidation saw it. Every // cached exchange, denomination and refresh cost now describes records that // are gone. + await wex.runWalletDbTx((tx) => scheduleAttentionExpirations(wex, tx)); + wex.ws.notify({ type: NotificationType.UserAttentionChanged }); wex.ws.clearAllCaches(); return {}; } @@ -3003,6 +3021,8 @@ const handlers: { [T in WalletApiOperation]: HandlerWithValidator<T> } = { codec: codecForEmptyObject(), handler: async (wex, req) => { await wex.ws.db.clearDatabase(); + await wex.runWalletDbTx((tx) => scheduleAttentionExpirations(wex, tx)); + wex.ws.notify({ type: NotificationType.UserAttentionChanged }); wex.ws.flightRecords = []; wex.ws.clearAllCaches(); await wex.taskScheduler.reload(); @@ -3091,6 +3111,44 @@ const handlers: { [T in WalletApiOperation]: HandlerWithValidator<T> } = { codec: codecForInitiatePeerPushDebitRequest(), handler: initiatePeerPushDebit, }, + [WalletApiOperation.GetUserAttention]: { + codec: codecForEmptyObject(), + handler: getUserAttention, + }, + [WalletApiOperation.GetUserAttentionSummary]: { + codec: codecForEmptyObject(), + handler: (wex) => + wex.runWalletDbTx(async (tx) => ({ + unreadCount: await tx.countUnreadAttention( + AbsoluteTime.toStampMs(AbsoluteTime.now()), + ), + })), + }, + [WalletApiOperation.ObserveUserAttention]: { + codec: codecForObserveUserAttentionRequest(), + handler: async (wex, req) => { + await wex.ws.observations.registerUserAttention(req.observationId, () => + getUserAttention(wex), + ); + return {}; + }, + }, + [WalletApiOperation.MarkUserAttentionRead]: { + codec: attentionIdCodec, + handler: (wex, req) => updateAttention(wex, req.attentionId, false), + }, + [WalletApiOperation.MarkAllUserAttentionRead]: { + codec: codecForEmptyObject(), + handler: markAllUserAttentionRead, + }, + [WalletApiOperation.ClearReadUserAttention]: { + codec: codecForEmptyObject(), + handler: clearReadUserAttention, + }, + [WalletApiOperation.DismissUserAttention]: { + codec: attentionIdCodec, + handler: (wex, req) => updateAttention(wex, req.attentionId, true), + }, [WalletApiOperation.ObserveTransaction]: { codec: codecForObserveTransactionRequest(), handler: observeTransaction, diff --git a/packages/taler-wallet-core/src/user-attention.ts b/packages/taler-wallet-core/src/user-attention.ts @@ -0,0 +1,162 @@ +/* + * This file is part of GNU Taler + * (C) 2026 Taler Systems S.A. + * SPDX-License-Identifier: GPL-3.0-or-later + */ +import { + AbsoluteTime, + NotificationType, + TalerError, + TalerErrorCode, + TalerPreciseTimestamp, + type TimerHandle, + type UserAttentionItem, + type UserAttentionSnapshot, +} from "@gnu-taler/taler-util"; +import type { WalletUserAttention } from "./db/records.js"; +import type { WalletDbTransaction } from "./db/transaction.js"; +import type { WalletExecutionContext } from "./wallet.js"; + +const nowMs = () => AbsoluteTime.toStampMs(AbsoluteTime.now()); +const stampMs = (stamp: TalerPreciseTimestamp) => + stamp.t_s === "never" + ? Number.MAX_SAFE_INTEGER + : stamp.t_s * 1000 + (stamp.off_us ?? 0) / 1000; +function active(row: WalletUserAttention, now: number) { + return ( + !row.dismissed && (!row.item.expiresAt || stampMs(row.item.expiresAt) > now) + ); +} +function changed(tx: WalletDbTransaction) { + tx.notify({ type: NotificationType.UserAttentionChanged }); +} +async function save( + tx: WalletDbTransaction, + sourceKey: string, + item: UserAttentionItem, + dismissed = false, +) { + const unreadUntil = + dismissed || item.readAt + ? 0 + : item.expiresAt + ? stampMs(item.expiresAt) + : Number.MAX_SAFE_INTEGER; + await tx.upsertUserAttention({ sourceKey, item, unreadUntil, dismissed }); +} + +export async function getUserAttention( + wex: WalletExecutionContext, +): Promise<UserAttentionSnapshot> { + return wex.runWalletDbTx(async (tx) => { + const now = nowMs(); + const items = (await tx.listUserAttention()) + .filter((row) => active(row, now)) + .map((row) => row.item); + items.sort( + (a, b) => + stampMs(b.createdAt) - stampMs(a.createdAt) || + a.attentionId.localeCompare(b.attentionId), + ); + return { items, unreadCount: items.filter((item) => !item.readAt).length }; + }); +} + +export async function updateAttention( + wex: WalletExecutionContext, + id: string, + dismiss: boolean, +) { + await wex.runWalletDbTx(async (tx) => { + const row = await tx.getUserAttentionById(id); + if (!row || !active(row, nowMs())) return; + if (dismiss && !row.item.dismissible) + throw TalerError.fromDetail( + TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, + { parameter: "attentionId" }, + "This attention item cannot be dismissed", + ); + if (!dismiss && row.item.readAt) return; + if (!dismiss) row.item.readAt = TalerPreciseTimestamp.now(); + // Keep the identity of a dismissed spend so repeated conflict handling cannot resurrect it. + await save(tx, row.sourceKey, row.item, dismiss); + if (dismiss && row.item.expiresAt) + await scheduleAttentionExpirations(wex, tx); + changed(tx); + }); + return {}; +} + +export async function markAllUserAttentionRead(wex: WalletExecutionContext) { + await wex.runWalletDbTx(async (tx) => { + const readAt = TalerPreciseTimestamp.now(); + const now = stampMs(readAt); + const unread = (await tx.listUserAttention()).filter( + (row) => active(row, now) && !row.item.readAt, + ); + for (const { sourceKey, item } of unread) { + await save(tx, sourceKey, { ...item, readAt }); + } + if (unread.length) changed(tx); + }); + return {}; +} + +export async function clearReadUserAttention(wex: WalletExecutionContext) { + await wex.runWalletDbTx(async (tx) => { + const now = nowMs(); + const clearable = (await tx.listUserAttention()).filter( + (row) => active(row, now) && row.item.readAt && row.item.dismissible, + ); + if (!clearable.length) return; + for (const { sourceKey, item } of clearable) { + await save(tx, sourceKey, item, true); + } + if (clearable.some((row) => row.item.expiresAt)) + await scheduleAttentionExpirations(wex, tx); + changed(tx); + }); + return {}; +} + +// A deadline also wakes clients that only requested the home-screen count. +const expiryTimers = new WeakMap<WalletExecutionContext["ws"], TimerHandle>(); +export async function scheduleAttentionExpirations( + wex: WalletExecutionContext, + tx: WalletDbTransaction, +) { + const now = nowMs(); + const deadlines = [ + ...new Set( + (await tx.listUserAttention()).flatMap((row) => + active(row, now) && row.item.expiresAt + ? [stampMs(row.item.expiresAt)] + : [], + ), + ), + ].sort((a, b) => a - b); + tx.scheduleOnCommit(() => { + expiryTimers.get(wex.ws)?.clear(); + const schedule = () => { + const at = deadlines[0]; + if (at === undefined) { + expiryTimers.delete(wex.ws); + return; + } + const timer = wex.ws.timerGroup.after( + Math.min(0x7fffffff, Math.max(0, Math.ceil(at - nowMs()))), + () => { + const when = nowMs(); + if (when >= at) { + while (deadlines.length && deadlines[0] <= when) deadlines.shift(); + wex.ws.notify({ type: NotificationType.UserAttentionChanged }); + } + schedule(); + }, + ); + expiryTimers.set(wex.ws, timer); + timer.unref(); + }; + schedule(); + }); +} diff --git a/packages/taler-wallet-core/src/wallet-api-types.ts b/packages/taler-wallet-core/src/wallet-api-types.ts @@ -27,6 +27,7 @@ import { AbortTransactionRequest, AcceptBankIntegratedWithdrawalRequest, AcceptExchangeTosRequest, + UserAttentionSnapshot, ConfirmExchangeKeyChangeRequest, AcceptManualWithdrawalRequest, AcceptManualWithdrawalResult, @@ -174,6 +175,7 @@ import { ObserveBalanceRefreshInfoRequest, BalanceRefreshInfoRequest, WalletRefreshInfo, + ObserveUserAttentionRequest, StopObservationRequest, PreparePeerPushCreditRequest, PreparePeerPushCreditResponse, @@ -357,6 +359,13 @@ export enum WalletApiOperation { // P2P Payments ObserveTransaction = "observeTransaction", + GetUserAttention = "getUserAttention", + GetUserAttentionSummary = "getUserAttentionSummary", + ObserveUserAttention = "observeUserAttention", + MarkUserAttentionRead = "markUserAttentionRead", + MarkAllUserAttentionRead = "markAllUserAttentionRead", + ClearReadUserAttention = "clearReadUserAttention", + DismissUserAttention = "dismissUserAttention", StopObservation = "stopObservation", PreparePeerPushCredit = "preparePeerPushCredit", CheckPeerPushDebit = "checkPeerPushDebit", @@ -1418,7 +1427,56 @@ export type ObserveTransactionOp = { response: EmptyObject; }; -/** End an observation without changing the observed transaction. */ +/** List active items, newest first, and their unread count. */ +export type GetUserAttentionOp = { + op: WalletApiOperation.GetUserAttention; + request: EmptyObject; + response: UserAttentionSnapshot; +}; + +/** Read the badge count on startup and on user-attention-changed. */ +export type GetUserAttentionSummaryOp = { + op: WalletApiOperation.GetUserAttentionSummary; + request: EmptyObject; + response: { unreadCount: number }; +}; + +/** Subscribe to revisioned inbox snapshots until stopObservation. */ +export type ObserveUserAttentionOp = { + op: WalletApiOperation.ObserveUserAttention; + request: ObserveUserAttentionRequest; + response: EmptyObject; +}; + +/** Mark one occurrence read. Repeating this operation is harmless. */ +export type MarkUserAttentionReadOp = { + op: WalletApiOperation.MarkUserAttentionRead; + request: { attentionId: string }; + response: EmptyObject; +}; + +/** Mark all currently active unread occurrences as read in one transaction. */ +export type MarkAllUserAttentionReadOp = { + op: WalletApiOperation.MarkAllUserAttentionRead; + request: EmptyObject; + response: EmptyObject; +}; + +/** Dismiss all currently active occurrences that are both read and dismissible. */ +export type ClearReadUserAttentionOp = { + op: WalletApiOperation.ClearReadUserAttention; + request: EmptyObject; + response: EmptyObject; +}; + +/** Remove a dismissible occurrence from the inbox. */ +export type DismissUserAttentionOp = { + op: WalletApiOperation.DismissUserAttention; + request: { attentionId: string }; + response: EmptyObject; +}; + +/** End an observation. */ export type StopObservationOp = { op: WalletApiOperation.StopObservation; request: StopObservationRequest; @@ -2018,6 +2076,12 @@ export const walletApiExpectedErrors = { TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, TalerErrorCode.WALLET_TRANSACTION_NOT_FOUND, ], + [WalletApiOperation.DismissUserAttention]: [ + TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, + ], + [WalletApiOperation.ObserveUserAttention]: [ + TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, + ], [WalletApiOperation.StopObservation]: [ TalerErrorCode.WALLET_CORE_API_BAD_REQUEST, ], @@ -2253,6 +2317,13 @@ export type WalletOperations = { [WalletApiOperation.CheckPeerPushDebitV2]: CheckPeerPushDebitV2Op; [WalletApiOperation.InitiatePeerPushDebit]: InitiatePeerPushDebitOp; [WalletApiOperation.ObserveTransaction]: ObserveTransactionOp; + [WalletApiOperation.GetUserAttention]: GetUserAttentionOp; + [WalletApiOperation.GetUserAttentionSummary]: GetUserAttentionSummaryOp; + [WalletApiOperation.ObserveUserAttention]: ObserveUserAttentionOp; + [WalletApiOperation.MarkUserAttentionRead]: MarkUserAttentionReadOp; + [WalletApiOperation.MarkAllUserAttentionRead]: MarkAllUserAttentionReadOp; + [WalletApiOperation.ClearReadUserAttention]: ClearReadUserAttentionOp; + [WalletApiOperation.DismissUserAttention]: DismissUserAttentionOp; [WalletApiOperation.StopObservation]: StopObservationOp; [WalletApiOperation.PreparePeerPushCredit]: PreparePeerPushCreditOp; [WalletApiOperation.ConfirmPeerPushCredit]: ConfirmPeerPushCreditOp; diff --git a/packages/taler-wallet-core/src/wallet-notifications.test.ts b/packages/taler-wallet-core/src/wallet-notifications.test.ts @@ -55,6 +55,11 @@ import { WithdrawalRecordType, WithdrawalGroupStatus, } from "./db/records.js"; +import { + clearReadUserAttention, + getUserAttention, + markAllUserAttentionRead, +} from "./user-attention.js"; import { runnerFactories } from "./db/testing/runners.js"; import { getBalances } from "./balance.js"; import { @@ -280,6 +285,86 @@ async function fixture(makeRunner: (typeof runnerFactories)[number]) { } for (const makeRunner of runnerFactories) { + test(`${makeRunner.name}: bulk attention updates skip expired items and emit one change per effective operation`, async () => { + const f = await fixture(makeRunner); + try { + const readCondition = { + type: "refresh-blocked-for-debugging", + attentionId: "condition", + createdAt: { t_s: 1 }, + readAt: { t_s: 2 }, + dismissible: false, + } as const; + // Each bulk operation should change multiple live rows in one commit. + await f.db.runReadWriteTx(async (tx) => { + await tx.upsertUserAttention({ + sourceKey: "condition", + item: readCondition, + unreadUntil: 0, + }); + for (const group of ["live-a", "live-b", "expired"]) { + const expired = group === "expired"; + for (const read of [false, true]) { + const id = group + (read ? "-read" : "-unread"); + await tx.upsertUserAttention({ + sourceKey: id, + item: { + type: "coin-double-spent", + exchangeBaseUrls: [exchangeUrl], + amountSpentElsewhere: "TESTKUDOS:1", + attentionId: id, + createdAt: { t_s: 1 }, + dismissible: true, + ...(read && { readAt: { t_s: 2 } }), + ...(expired && { expiresAt: { t_s: 3 } }), + }, + unreadUntil: read ? 0 : expired ? 3000 : Number.MAX_SAFE_INTEGER, + }); + } + } + }); + const rows = () => f.db.runReadWriteTx((tx) => tx.listUserAttention()); + const expiredBefore = (await rows()).filter((r) => r.item.expiresAt); + const attentionEvents = () => + f.notifications.filter( + (n) => n.type === NotificationType.UserAttentionChanged, + ).length; + await clearReadUserAttention(f.wex); + await tick(); + assert.equal(attentionEvents(), 1); + assert.deepEqual( + (await getUserAttention(f.wex)).items.map((i) => i.attentionId), + ["condition", "live-a-unread", "live-b-unread"], + ); + await clearReadUserAttention(f.wex); + await tick(); + assert.equal(attentionEvents(), 1); + await markAllUserAttentionRead(f.wex); + await markAllUserAttentionRead(f.wex); + await tick(); + assert.equal(attentionEvents(), 2); + await clearReadUserAttention(f.wex); + await clearReadUserAttention(f.wex); + await tick(); + assert.equal(attentionEvents(), 3); + assert.deepEqual(await getUserAttention(f.wex), { + items: [readCondition], + unreadCount: 0, + }); + const remaining = await rows(); + assert.deepEqual( + remaining.filter((r) => r.item.expiresAt), + expiredBefore, + ); + assert.equal(remaining.filter((r) => r.dismissed).length, 4); + assert.ok( + !f.notifications.some((n) => n.type === NotificationType.BalanceChange), + ); + } finally { + await f.close(); + } + }); + test(`${makeRunner.name}: exchange retry publishes changed errors and their removal`, async () => { const f = await fixture(makeRunner); try { diff --git a/packages/taler-wallet-core/src/wallet.ts b/packages/taler-wallet-core/src/wallet.ts @@ -52,6 +52,7 @@ import { Logger, LongpollQueue, NotificationType, + ObservationType, ObservabilityContext, ObservabilityEventType, ObservableHttpClientLibrary, @@ -1884,6 +1885,8 @@ export class InternalWalletState { notify(n: WalletNotification): void { logger.trace(`Notification: ${j2s(n)}`); + if (n.type === NotificationType.UserAttentionChanged) + this.observations.invalidate(ObservationType.UserAttention); if (n.type === NotificationType.BalanceChange) { for (const id of this.taskScheduler.getActiveTasks()) { if (id.startsWith(`${PendingTaskType.ExchangeAutoRefresh}:`)) diff --git a/packages/wallet-webui/src/api/notifications.ts b/packages/wallet-webui/src/api/notifications.ts @@ -5,6 +5,7 @@ import { import { WalletApiOperation } from "@gnu-taler/taler-wallet-core"; export type WalletKeyFamily = + | "user-attention" | "balances" | "transactions" | "exchanges" @@ -15,6 +16,10 @@ export type WalletKeyFamily = | "diagnostics"; export const familyOperations: Record<WalletKeyFamily, readonly string[]> = { + "user-attention": [ + WalletApiOperation.GetUserAttentionSummary, + WalletApiOperation.GetUserAttention, + ], balances: [ WalletApiOperation.GetBalances, WalletApiOperation.GetBalanceDetail, @@ -47,6 +52,8 @@ export function notificationFamilies( notification: WalletNotification, ): readonly WalletKeyFamily[] { switch (notification.type) { + case NotificationType.UserAttentionChanged: + return ["user-attention"]; case NotificationType.BalanceChange: return ["balances", "transactions", "tokens"]; case NotificationType.TransactionStateTransition: diff --git a/packages/wallet-webui/src/platform/observation-owner.ts b/packages/wallet-webui/src/platform/observation-owner.ts @@ -31,6 +31,7 @@ export class ObservationOwner { typeof args?.observationId === "string" ? args.observationId : undefined; const registering = (request.operation === WalletApiOperation.ObserveTransaction || + request.operation === WalletApiOperation.ObserveUserAttention || request.operation === WalletApiOperation.ObserveBalanceRefreshInfo) && id !== undefined; if (registering) this.registering.add(id); diff --git a/packages/wallet-webui/test/notifications.test.ts b/packages/wallet-webui/test/notifications.test.ts @@ -37,3 +37,11 @@ test("transaction transitions refresh lists without reloading observed details", assert.equal(operations.has(WalletApiOperation.GetTransactionById), false); assert(!operations.has(WalletApiOperation.GetBalances)); }); + +test("a user attention change refreshes the badge independently of balances", () => { + const ops = operationsForNotification({ + type: NotificationType.UserAttentionChanged, + }); + assert(ops.has(WalletApiOperation.GetUserAttentionSummary)); + assert(!ops.has(WalletApiOperation.GetBalances)); +});