feat: let the frontend and API clients send notifications

Notifications could only come from backend code, and only in the kinds the
web client knows how to translate. Anyone can now send one that carries its
own text.

- A notification can carry its own title, body, icon and in-app link. RomM's
  own kinds stay translated; `custom` and any other kind (`argosy.sync_done`)
  is shown with its own content.
- POST /api/notifications: anyone with me.write notifies themselves; an admin
  can also notify user ids, `admins` or `all`, and is shown as the sender.
  RomM's own kinds are reserved, links must stay inside RomM, and `data` is
  capped at 4 KB.
- notify()/notify_admins() accept the same title/body/link/icon.
- Frontend: `snackbar.success(msg, { persist: true })` (or
  `{ persist: { body, link } }`) also keeps the message in the inbox. The
  first of the request's answer or the socket push shows the toast, so it
  appears once.
- Documented in BACKEND_ARCHITECTURE and the backend and frontend skills.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
zurdi
2026-09-23 12:12:55 +02:00
parent ff6b160117
commit 8b25efa2aa
23 changed files with 667 additions and 59 deletions

View File

@@ -55,6 +55,7 @@ alembic/ Migrations (env.py + versions/)
- **Model / schema change:** edit `models/`, then create a migration (below). Update the matching response schema so OpenAPI stays accurate.
- **Metadata provider:** add a typed client in `adapters/services/<name>.py` (+ `<name>_types.py`) and a `handler/metadata/<name>_handler.py` that normalizes into the common shape and slots into the priority order.
- **Background job:** subclass `Task`/`PeriodicTask` in `tasks/scheduled/` or `tasks/manual/`; register scheduled jobs in `startup.py`.
- **Telling a user something happened:** `notify()` / `notify_admins()` in `handler/notification_handler.py`, from a request or a worker. A `NotificationKind` is translated client-side from `data` (add its describer and locale keys); for anything else pass a free-form kind with `title`/`body`/`link`.
## Database migrations (Alembic)

View File

@@ -12,6 +12,7 @@ How v2 features behave. Each pattern has one canonical mechanism — don't inven
## A. Errors & snackbars
- Single channel: `useSnackbar()` (`src/v2/composables/useSnackbar/`) with `success | error | warning | info` methods. It emits `snackbarShow`; `NotificationHost` stacks toasts.
- Something the user should still find after the toast fades (a background upload finished, a long job failed) passes `{ persist: true }`, or `{ persist: { body, link } }` with an in-app path: it also lands in their notifications.
- The **call site** decides what's significant — no global "wrap-every-promise" magic.
- Field validation errors render **in-place**, never as a snackbar.
- Auth (401/403) is handled by the axios interceptor; no per-call-site checks.

View File

@@ -29,6 +29,10 @@ def upgrade() -> None:
sa.Column("actor_id", sa.Integer(), nullable=True),
sa.Column("kind", sa.String(length=64), nullable=False),
sa.Column("level", sa.String(length=16), nullable=False),
sa.Column("title", sa.String(length=255), nullable=True),
sa.Column("body", sa.String(length=1000), nullable=True),
sa.Column("link", sa.String(length=1000), nullable=True),
sa.Column("icon", sa.String(length=64), nullable=True),
sa.Column("data", CustomJSON(), nullable=True),
sa.Column("read_at", sa.TIMESTAMP(timezone=True), nullable=True),
sa.Column(

View File

@@ -1,14 +1,22 @@
from fastapi import HTTPException, Request, status
from decorators.auth import protected_route
from endpoints.responses.notification import NotificationIdsPayload, NotificationSchema
from endpoints.responses.notification import (
NotificationCreatePayload,
NotificationIdsPayload,
NotificationSchema,
)
from handler.auth.constants import Scope
from handler.auth.dependencies import assert_admin
from handler.database import db_notification_handler
from handler.notification_handler import (
NOTIFICATIONS_DISMISSED_EVENT,
NOTIFICATIONS_READ_EVENT,
deliver,
emit_to_user,
recipient_ids,
)
from models.notification import Notification
from utils.router import APIRouter
router = APIRouter(
@@ -26,6 +34,46 @@ def get_notifications(request: Request) -> list[NotificationSchema]:
]
@protected_route(router.post, "", [Scope.ME_WRITE], status_code=status.HTTP_201_CREATED)
async def create_notification(
request: Request, payload: NotificationCreatePayload
) -> list[NotificationSchema]:
"""Notify the caller or, for an admin, other users; returns what was sent.
Other users see the caller as its sender.
"""
sender_id = request.user.id
if payload.recipients is None or payload.recipients == [sender_id]:
user_ids = [sender_id]
else:
assert_admin(request)
user_ids = recipient_ids(payload.recipients)
if isinstance(payload.recipients, list):
missing = set(payload.recipients) - set(user_ids)
if missing:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"No enabled user with id {', '.join(map(str, sorted(missing)))}",
)
return [
await deliver(
Notification(
user_id=user_id,
actor_id=sender_id if user_id != sender_id else None,
kind=payload.kind,
level=payload.level,
title=payload.title,
body=payload.body,
link=payload.link,
icon=payload.icon,
data=payload.data,
)
)
for user_id in user_ids
]
@protected_route(router.post, "/read", [Scope.ME_WRITE])
async def mark_notifications_read(
request: Request, payload: NotificationIdsPayload

View File

@@ -1,8 +1,18 @@
from typing import Any
import json
from typing import Any, Literal
from pydantic import ConfigDict, field_validator
from pydantic import ConfigDict, Field, field_validator
from models.notification import NotificationKind, NotificationLevel
from models.notification import (
NOTIFICATION_BODY_MAX_LENGTH,
NOTIFICATION_DATA_MAX_LENGTH,
NOTIFICATION_ICON_MAX_LENGTH,
NOTIFICATION_KIND_MAX_LENGTH,
NOTIFICATION_LINK_MAX_LENGTH,
NOTIFICATION_TITLE_MAX_LENGTH,
NotificationKind,
NotificationLevel,
)
from .base import BaseModel, UTCDatetime
@@ -23,6 +33,10 @@ class NotificationSchema(BaseModel):
# A row written under a kind a later version dropped must still list.
kind: NotificationKind | str
level: NotificationLevel
title: str | None
body: str | None
link: str | None
icon: str | None
data: dict[str, Any]
actor: NotificationActorSchema | None
read_at: UTCDatetime | None
@@ -34,6 +48,68 @@ class NotificationSchema(BaseModel):
return value or {}
class NotificationCreatePayload(BaseModel):
"""A notification sent through the API, shown with its own title and body."""
title: str = Field(min_length=1, max_length=NOTIFICATION_TITLE_MAX_LENGTH)
body: str | None = Field(default=None, max_length=NOTIFICATION_BODY_MAX_LENGTH)
level: NotificationLevel = NotificationLevel.INFO
# Lets a client tell its own notifications apart, e.g. `argosy.sync_done`.
kind: str = Field(
default=NotificationKind.CUSTOM,
max_length=NOTIFICATION_KIND_MAX_LENGTH,
pattern=r"^[a-z0-9][a-z0-9_.:-]*$",
)
link: str | None = Field(
default=None,
max_length=NOTIFICATION_LINK_MAX_LENGTH,
description="A path inside RomM, such as `/rom/12`.",
)
icon: str | None = Field(
default=None,
max_length=NOTIFICATION_ICON_MAX_LENGTH,
pattern=r"^mdi-[a-z0-9-]+$",
description="A Material Design Icons name, such as `mdi-sync`.",
)
data: dict[str, Any] = Field(default_factory=dict)
recipients: list[int] | Literal["admins", "all"] | None = Field(
default=None,
description="User ids, `admins` or `all`; only an admin may notify "
"anyone but themselves. Null notifies the caller.",
)
@field_validator("kind")
@classmethod
def _kind_not_reserved(cls, value: str) -> str:
# Stops a client passing itself off as one of RomM's own events.
if value != NotificationKind.CUSTOM and value in NotificationKind:
raise ValueError(f"'{value}' is reserved for RomM's own notifications")
return value
@field_validator("data")
@classmethod
def _data_fits(cls, value: dict[str, Any]) -> dict[str, Any]:
if len(json.dumps(value)) > NOTIFICATION_DATA_MAX_LENGTH:
raise ValueError(
f"data must serialize to at most {NOTIFICATION_DATA_MAX_LENGTH} characters"
)
return value
@field_validator("link")
@classmethod
def _link_stays_in_app(cls, value: str | None) -> str | None:
if value is None:
return None
if (
not value.startswith("/")
or value.startswith("//")
or "\\" in value
or any(char.isspace() for char in value)
):
raise ValueError("link must be a path inside RomM, such as /rom/12")
return value
class NotificationIdsPayload(BaseModel):
"""Targets some of the caller's notifications, or all of them when `ids` is null."""

View File

@@ -1,10 +1,11 @@
"""Persistent per-user notifications, stored first and then pushed to open tabs.
Every entry point swallows its own failures: the caller is usually a job whose
outcome must not hinge on reporting it.
`notify` and `notify_admins` swallow their own failures: the caller is usually
a job whose outcome must not hinge on reporting it.
"""
from typing import Any
from collections.abc import Sequence
from typing import Any, Literal
import socketio
@@ -28,46 +29,85 @@ async def emit_to_user(user_id: int, event: str, payload: dict[str, Any]) -> Non
log.warning(f"Failed to push {event} to user {user_id}", exc_info=True)
async def deliver(notification: Notification) -> NotificationSchema:
"""Store a notification and push it to its user's open tabs; raises if it can't be stored."""
stored = NotificationSchema.model_validate(
db_notification_handler.add_notification(notification)
)
await emit_to_user(
notification.user_id, NOTIFICATIONS_NEW_EVENT, stored.model_dump(mode="json")
)
return stored
def recipient_ids(recipients: Sequence[int] | Literal["admins", "all"]) -> list[int]:
"""The enabled users among the given ids, or among every admin or user."""
if recipients == "admins":
users = list(db_user_handler.get_admin_users())
elif recipients == "all":
users = list(db_user_handler.get_users())
else:
users = [
user
for user_id in dict.fromkeys(recipients)
if (user := db_user_handler.get_user(user_id))
]
return [user.id for user in users if user.enabled]
async def notify(
user_id: int,
kind: NotificationKind,
kind: NotificationKind | str,
level: NotificationLevel,
data: dict[str, Any] | None = None,
actor_id: int | None = None,
*,
title: str | None = None,
body: str | None = None,
link: str | None = None,
icon: str | None = None,
) -> None:
"""Store a notification for one user and push it to their open tabs."""
"""Notify one user.
A kind RomM's client knows is shown translated from `data`; any other, like
`custom`, is shown with `title`, `body`, `link` (an in-app path) and `icon`.
"""
try:
notification = db_notification_handler.add_notification(
await deliver(
Notification(
user_id=user_id,
actor_id=actor_id,
kind=kind,
level=level,
title=title,
body=body,
link=link,
icon=icon,
data=data or {},
)
)
payload = NotificationSchema.model_validate(notification).model_dump(
mode="json"
)
except Exception: # noqa: BLE001
log.exception(f"Failed to store {kind} notification for user {user_id}")
return
await emit_to_user(user_id, NOTIFICATIONS_NEW_EVENT, payload)
async def notify_admins(
kind: NotificationKind,
kind: NotificationKind | str,
level: NotificationLevel,
data: dict[str, Any] | None = None,
*,
title: str | None = None,
body: str | None = None,
link: str | None = None,
icon: str | None = None,
) -> None:
"""Notify every enabled admin, for what the system did on nobody's behalf."""
try:
admins = db_user_handler.get_admin_users()
admin_ids = recipient_ids("admins")
except Exception: # noqa: BLE001
log.exception(f"Failed to look up the admins to notify of {kind}")
return
for admin in admins:
if admin.enabled:
await notify(admin.id, kind, level, data)
for admin_id in admin_ids:
await notify(
admin_id, kind, level, data, title=title, body=body, link=link, icon=icon
)

View File

@@ -2,7 +2,7 @@ from __future__ import annotations
import enum
from datetime import datetime
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Final
from sqlalchemy import TIMESTAMP, ForeignKey, Index, String
from sqlalchemy.orm import Mapped, mapped_column, relationship
@@ -22,8 +22,12 @@ class NotificationLevel(enum.StrEnum):
class NotificationKind(enum.StrEnum):
"""What happened. The client renders the text from it, in the reader's language."""
"""What happened. The client renders these in the reader's language.
Any other kind, `custom` included, is rendered from its own title and body.
"""
CUSTOM = "custom"
SCAN_COMPLETED = "scan_completed"
SCAN_FAILED = "scan_failed"
TASK_COMPLETED = "task_completed"
@@ -32,6 +36,15 @@ class NotificationKind(enum.StrEnum):
ROLE_CHANGED = "role_changed"
NOTIFICATION_KIND_MAX_LENGTH: Final = 64
NOTIFICATION_TITLE_MAX_LENGTH: Final = 255
NOTIFICATION_BODY_MAX_LENGTH: Final = 1000
NOTIFICATION_LINK_MAX_LENGTH: Final = 1000
NOTIFICATION_ICON_MAX_LENGTH: Final = 64
# Of `data` serialized as JSON, for what API clients send.
NOTIFICATION_DATA_MAX_LENGTH: Final = 4096
class Notification(BaseModel):
__tablename__ = "notifications"
__table_args__ = (
@@ -48,8 +61,21 @@ class Notification(BaseModel):
ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True
)
# Strings rather than database enums, so a new kind needs no migration.
kind: Mapped[str] = mapped_column(String(64))
kind: Mapped[str] = mapped_column(String(NOTIFICATION_KIND_MAX_LENGTH))
level: Mapped[str] = mapped_column(String(16))
title: Mapped[str | None] = mapped_column(
String(NOTIFICATION_TITLE_MAX_LENGTH), nullable=True
)
body: Mapped[str | None] = mapped_column(
String(NOTIFICATION_BODY_MAX_LENGTH), nullable=True
)
# An in-app path (`/rom/12`), never an external URL.
link: Mapped[str | None] = mapped_column(
String(NOTIFICATION_LINK_MAX_LENGTH), nullable=True
)
icon: Mapped[str | None] = mapped_column(
String(NOTIFICATION_ICON_MAX_LENGTH), nullable=True
)
# The values the kind's text is built from (names, counts, ids to link to).
data: Mapped[dict[str, Any] | None] = mapped_column(CustomJSON(), default=dict)
read_at: Mapped[datetime | None] = mapped_column(

View File

@@ -154,3 +154,111 @@ def test_an_inbox_keeps_only_the_newest(admin_user):
assert len(remaining) == MAX_NOTIFICATIONS_PER_USER
assert oldest.id not in {n.id for n in remaining}
class TestCreateNotification:
def test_a_user_notifies_themselves(
self, client, viewer_access_token, viewer_user, emit
):
response = client.post(
"/api/notifications",
json={
"title": "Sync finished",
"body": "12 saves uploaded",
"kind": "argosy.sync_done",
"level": "success",
"link": "/rom/12",
"icon": "mdi-sync",
"data": {"device": "deck"},
},
headers=_auth(viewer_access_token),
)
assert response.status_code == status.HTTP_201_CREATED
[sent] = response.json()
assert sent["title"] == "Sync finished"
assert sent["kind"] == "argosy.sync_done"
assert sent["actor"] is None
[stored] = db_notification_handler.get_notifications(viewer_user.id)
assert (stored.link, stored.data) == ("/rom/12", {"device": "deck"})
emit.assert_awaited_once()
def test_only_an_admin_notifies_others(
self, client, viewer_access_token, admin_user, emit
):
response = client.post(
"/api/notifications",
json={"title": "Hello", "recipients": [admin_user.id]},
headers=_auth(viewer_access_token),
)
assert response.status_code == status.HTTP_403_FORBIDDEN
assert db_notification_handler.get_notifications(admin_user.id) == []
def test_an_admin_notifies_everyone_as_the_sender(
self, client, access_token, admin_user, viewer_user, editor_user, emit
):
response = client.post(
"/api/notifications",
json={
"title": "Maintenance tonight",
"level": "warning",
"recipients": "all",
},
headers=_auth(access_token),
)
assert response.status_code == status.HTTP_201_CREATED
assert len(response.json()) == 3
[to_viewer] = db_notification_handler.get_notifications(viewer_user.id)
assert to_viewer.actor_id == admin_user.id
[to_self] = db_notification_handler.get_notifications(admin_user.id)
assert to_self.actor_id is None
def test_an_admin_notifies_only_the_admins(
self, client, access_token, admin_user, viewer_user, emit
):
client.post(
"/api/notifications",
json={"title": "Disk almost full", "recipients": "admins"},
headers=_auth(access_token),
)
assert len(db_notification_handler.get_notifications(admin_user.id)) == 1
assert db_notification_handler.get_notifications(viewer_user.id) == []
def test_an_unknown_recipient_is_not_found(
self, client, access_token, viewer_user, emit
):
response = client.post(
"/api/notifications",
json={"title": "Hello", "recipients": [viewer_user.id, 999_999]},
headers=_auth(access_token),
)
assert response.status_code == status.HTTP_404_NOT_FOUND
assert db_notification_handler.get_notifications(viewer_user.id) == []
@pytest.mark.parametrize(
"field",
[
{"kind": "role_changed"},
{"link": "https://example.com"},
{"link": "//example.com/login"},
{"link": "/\\example.com"},
{"icon": "not-an-icon"},
{"title": ""},
{"data": {"blob": "x" * 5000}},
],
)
def test_rejects_what_a_client_may_not_send(
self, client, access_token, admin_user, field, emit
):
response = client.post(
"/api/notifications",
json={"title": "Hello", **field},
headers=_auth(access_token),
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
assert db_notification_handler.get_notifications(admin_user.id) == []

View File

@@ -53,6 +53,27 @@ class TestNotify:
assert payload["data"] == {"new_roms": 2}
assert payload["created_at"].startswith("2026-09-23")
async def test_carries_its_own_content_for_a_custom_kind(
self, emit, add_notification
):
await notify(
3,
"argosy.sync_done",
NotificationLevel.INFO,
title="Sync finished",
body="12 saves uploaded",
link="/rom/12",
icon="mdi-sync",
)
payload = emit.await_args.args[2]
assert payload["kind"] == "argosy.sync_done"
assert (payload["title"], payload["body"]) == (
"Sync finished",
"12 saves uploaded",
)
assert (payload["link"], payload["icon"]) == ("/rom/12", "mdi-sync")
async def test_a_storage_failure_pushes_nothing(self, mocker, emit):
mocker.patch.object(
notification_handler.db_notification_handler,
@@ -78,9 +99,8 @@ class TestNotifyAdmins:
await notify_admins(NotificationKind.TASK_FAILED, NotificationLevel.ERROR)
notify_mock.assert_awaited_once_with(
1, NotificationKind.TASK_FAILED, NotificationLevel.ERROR, None
)
assert notify_mock.await_count == 1
assert notify_mock.await_args.args[0] == 1
class TestEmitToUser:

View File

@@ -1008,7 +1008,25 @@ Facet endpoints (`/artists`, `/albums`, `/genres`, `/years`) return `{value, cou
| GET | `/{id}` | TASKS_RUN | Status of specific task |
| POST | `/run/{name}` | TASKS_RUN | Trigger task execution |
### 6.16 Other Endpoints
### 6.16 Notifications (`/api/notifications`)
| Method | Path | Scope | Description |
| ------ | ------- | -------- | ----------------------------------------------------------- |
| GET | `/` | ME_READ | Caller's notifications, newest first |
| POST | `/` | ME_WRITE | Send one to yourself; admins also to users, `admins`, `all` |
| POST | `/read` | ME_WRITE | Mark ids read (`ids: null` marks all) |
| DELETE | `/{id}` | ME_WRITE | Dismiss one for good |
| DELETE | `/` | ME_WRITE | Dismiss all |
A client's notification carries its own `title`, `body`, `icon` (`mdi-*`) and `link`, which must be a path inside RomM. RomM's own `kind`s are reserved; any other (`custom`, `argosy.sync_done`) is shown as sent.
```bash
curl -X POST "$ROMM/api/notifications" -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"title": "Sync finished", "body": "12 saves uploaded", "level": "success", "link": "/rom/12"}'
```
### 6.17 Other Endpoints
| Router | Path | Description |
| ------------- | -------------------------------------- | -------------------------------------- |
@@ -1262,6 +1280,17 @@ ScanStats:
scanned_firmware, new_firmware
```
### 8.9 Notifications (`handler/notification_handler.py`)
Persistent per-user notifications, kept until dismissed and pushed live to the user's `user:{id}` socket room. From backend code, web process or worker alike:
```python
await notify(user.id, NotificationKind.SCAN_COMPLETED, NotificationLevel.SUCCESS, stats)
await notify_admins("custom", NotificationLevel.WARNING, title="Disk almost full")
```
A `NotificationKind` is translated by the client from `data`; a new one needs a describer in `frontend/src/v2/utils/notifications.ts` and locale keys. Until then, or for a one-off, pass any other kind with `title`/`body`/`link`/`icon`. Both helpers log and swallow failures, so a job never fails over reporting itself.
---
## 9. External Integrations (Adapters)
@@ -1360,6 +1389,16 @@ Client ←──Socket.IO──→ FastAPI (python-socketio) ←──Redis P
| `scan:log` | Log message | Scan log entries |
| `scan:stop` | | Scan completed or cancelled |
### Notifications (`/ws`)
Sent to the user's own `user:{id}` room:
| Event | Payload | When |
| ------------------------- | ---------------------- | ---------------------------- |
| `notifications:new` | `NotificationSchema` | One was stored for the user |
| `notifications:read` | `{ids: int[] \| null}` | Another tab marked some read |
| `notifications:dismissed` | `{ids: int[] \| null}` | Another tab dismissed some |
### Netplay (`/netplay`)
**Events:**

View File

@@ -153,6 +153,7 @@ export type { MuteRequest } from './models/MuteRequest';
export type { MuteResponse } from './models/MuteResponse';
export type { NetplayICEServer } from './models/NetplayICEServer';
export type { NotificationActorSchema } from './models/NotificationActorSchema';
export type { NotificationCreatePayload } from './models/NotificationCreatePayload';
export type { NotificationIdsPayload } from './models/NotificationIdsPayload';
export type { NotificationKind } from './models/NotificationKind';
export type { NotificationLevel } from './models/NotificationLevel';

View File

@@ -0,0 +1,28 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { NotificationLevel } from './NotificationLevel';
/**
* A notification sent through the API, shown with its own title and body.
*/
export type NotificationCreatePayload = {
title: string;
body?: (string | null);
level?: NotificationLevel;
kind?: string;
/**
* A path inside RomM, such as `/rom/12`.
*/
link?: (string | null);
/**
* A Material Design Icons name, such as `mdi-sync`.
*/
icon?: (string | null);
data?: Record<string, any>;
/**
* User ids, `admins` or `all`; only an admin may notify anyone but themselves. Null notifies the caller.
*/
recipients?: (Array<number> | 'admins' | 'all' | null);
};

View File

@@ -3,6 +3,8 @@
/* tslint:disable */
/* eslint-disable */
/**
* What happened. The client renders the text from it, in the reader's language.
* What happened. The client renders these in the reader's language.
*
* Any other kind, `custom` included, is rendered from its own title and body.
*/
export type NotificationKind = 'scan_completed' | 'scan_failed' | 'task_completed' | 'task_failed' | 'streaming_session_ended' | 'role_changed';
export type NotificationKind = 'custom' | 'scan_completed' | 'scan_failed' | 'task_completed' | 'task_failed' | 'streaming_session_ended' | 'role_changed';

View File

@@ -9,6 +9,10 @@ export type NotificationSchema = {
id: number;
kind: (NotificationKind | string);
level: NotificationLevel;
title: (string | null);
body: (string | null);
link: (string | null);
icon: (string | null);
data: Record<string, any>;
actor: (NotificationActorSchema | null);
read_at: (string | null);

View File

@@ -1,10 +1,17 @@
import type { NotificationSchema } from "@/__generated__";
import type {
NotificationCreatePayload,
NotificationSchema,
} from "@/__generated__";
import api from "@/services/api";
async function getNotifications() {
return api.get<NotificationSchema[]>("/notifications");
}
async function create(payload: NotificationCreatePayload) {
return api.post<NotificationSchema[]>("/notifications", payload);
}
async function markRead(ids: number[] | null) {
return api.post("/notifications/read", { ids });
}
@@ -19,6 +26,7 @@ async function dismissAll() {
export default {
getNotifications,
create,
markRead,
dismiss,
dismissAll,

View File

@@ -40,8 +40,9 @@ export function installNotificationInbox() {
{ immediate: true },
);
// Already here when this tab sent it and the request answered first.
useSocketEvent<NotificationSchema>("notifications:new", (notification) => {
inbox.receive(notification);
if (!inbox.receive(notification)) return;
const view = describeNotification(notification);
if (view.toast) {
snackbar.show(notification.level, view.title, { icon: view.icon });

View File

@@ -0,0 +1,83 @@
import { flushPromises } from "@vue/test-utils";
import mitt from "mitt";
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { NotificationSchema } from "@/__generated__";
import type { Events } from "@/types/emitter";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import storeNotificationInbox from "@/v2/stores/notificationInbox";
const { create, emitter } = vi.hoisted(() => ({
create: vi.fn(),
emitter: { current: null as ReturnType<typeof mitt<Events>> | null },
}));
vi.mock("@/services/api/notification", () => ({ default: { create } }));
vi.mock("vue", async (importOriginal) => ({
...(await importOriginal<typeof import("vue")>()),
inject: () => emitter.current,
}));
const stored: NotificationSchema = {
id: 9,
kind: "custom",
level: "success",
title: "Upload finished",
body: null,
link: "/rom/12",
icon: null,
data: {},
actor: null,
read_at: null,
created_at: "2026-09-23T10:00:00+00:00",
};
describe("useSnackbar persist", () => {
const shown = vi.fn();
beforeEach(() => {
setActivePinia(createPinia());
vi.resetAllMocks();
emitter.current = mitt<Events>();
emitter.current.on("snackbarShow", shown);
});
it("keeps the message and shows it once", async () => {
create.mockResolvedValue({ data: [stored] });
useSnackbar().success("Upload finished", { persist: { link: "/rom/12" } });
await flushPromises();
expect(create).toHaveBeenCalledWith({
level: "success",
title: "Upload finished",
body: undefined,
link: "/rom/12",
icon: undefined,
});
expect(storeNotificationInbox().notifications).toEqual([stored]);
expect(shown).toHaveBeenCalledOnce();
expect(shown.mock.calls[0][0]).not.toHaveProperty("persist");
});
it("leaves the toast to the socket push when it got here first", async () => {
create.mockResolvedValue({ data: [stored] });
storeNotificationInbox().receive(stored);
useSnackbar().success("Upload finished", { persist: true });
await flushPromises();
expect(shown).not.toHaveBeenCalled();
});
it("still shows the message when it can't be kept", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
create.mockRejectedValue(new Error("offline"));
useSnackbar().error("Upload failed", { persist: true });
await flushPromises();
expect(shown).toHaveBeenCalledOnce();
});
});

View File

@@ -7,6 +7,7 @@
// const snackbar = useSnackbar();
// snackbar.success("Saved");
// snackbar.error("Upload failed", { timeout: 6000 });
// snackbar.success("Upload finished", { persist: { link: "/rom/12" } });
//
// Tones map to the four canonical kinds the NotificationHost collapses to:
// success | error | warning | info. When v1 dies the emitter payload can
@@ -14,6 +15,7 @@
import type { Emitter } from "mitt";
import { inject } from "vue";
import type { Events } from "@/types/emitter";
import storeNotificationInbox from "@/v2/stores/notificationInbox";
export type SnackbarTone = "success" | "error" | "warning" | "info";
@@ -26,6 +28,9 @@ export interface SnackbarOptions {
id?: number;
/** Artwork shown in place of the icon, e.g. the cover of the game it concerns. */
image?: string | null;
/** Also keeps it in the user's notifications, optionally with a detail
* line and an in-app link. */
persist?: boolean | { body?: string; link?: string };
}
const TONE_TO_COLOR: Record<SnackbarTone, string> = {
@@ -38,7 +43,11 @@ const TONE_TO_COLOR: Record<SnackbarTone, string> = {
export function useSnackbar() {
const emitter = inject<Emitter<Events>>("emitter");
function show(tone: SnackbarTone, msg: string, opts: SnackbarOptions = {}) {
function toast(
tone: SnackbarTone,
msg: string,
{ persist: _, ...opts }: SnackbarOptions,
) {
emitter?.emit("snackbarShow", {
msg,
color: TONE_TO_COLOR[tone],
@@ -46,6 +55,34 @@ export function useSnackbar() {
});
}
async function persist(
tone: SnackbarTone,
msg: string,
opts: SnackbarOptions,
) {
const extra = typeof opts.persist === "object" ? opts.persist : {};
try {
const inbox = storeNotificationInbox();
const notification = await inbox.send({
level: tone,
title: msg,
body: extra.body,
link: extra.link,
icon: opts.icon,
});
// The socket push can arrive first, and it shows the toast itself.
if (!inbox.receive(notification)) return;
} catch (error) {
console.error("Could not keep the notification:", error);
}
toast(tone, msg, opts);
}
function show(tone: SnackbarTone, msg: string, opts: SnackbarOptions = {}) {
if (opts.persist) void persist(tone, msg, opts);
else toast(tone, msg, opts);
}
return {
success(msg: string, opts?: SnackbarOptions) {
show("success", msg, opts);

View File

@@ -3,15 +3,18 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { NotificationSchema } from "@/__generated__";
import storeNotificationInbox from "@/v2/stores/notificationInbox";
const { dismiss, dismissAll, getNotifications, markRead } = vi.hoisted(() => ({
dismiss: vi.fn(),
dismissAll: vi.fn(),
getNotifications: vi.fn(),
markRead: vi.fn(),
}));
const { create, dismiss, dismissAll, getNotifications, markRead } = vi.hoisted(
() => ({
create: vi.fn(),
dismiss: vi.fn(),
dismissAll: vi.fn(),
getNotifications: vi.fn(),
markRead: vi.fn(),
}),
);
vi.mock("@/services/api/notification", () => ({
default: { dismiss, dismissAll, getNotifications, markRead },
default: { create, dismiss, dismissAll, getNotifications, markRead },
}));
function notification(
@@ -22,6 +25,10 @@ function notification(
id,
kind: "task_completed",
level: "success",
title: null,
body: null,
link: null,
icon: null,
data: {},
actor: null,
read_at: null,
@@ -52,12 +59,25 @@ describe("notificationInbox", () => {
const inbox = storeNotificationInbox();
inbox.receive(notification(1));
inbox.receive(notification(2));
inbox.receive(notification(2));
expect(inbox.receive(notification(2))).toBe(true);
expect(inbox.receive(notification(2))).toBe(false);
expect(inbox.notifications.map((n) => n.id)).toEqual([2, 1]);
});
it("sends a notification to the signed-in user", async () => {
create.mockResolvedValue({ data: [notification(5)] });
const inbox = storeNotificationInbox();
const sent = await inbox.send({ title: "Sync finished", level: "success" });
expect(create).toHaveBeenCalledWith({
title: "Sync finished",
level: "success",
});
expect(sent.id).toBe(5);
});
it("marks read what another tab read, or everything for null", () => {
const inbox = storeNotificationInbox();
inbox.notifications = [notification(1), notification(2), notification(3)];

View File

@@ -1,7 +1,10 @@
// notificationInbox (v2) — the signed-in user's notifications, newest first,
// kept current by `installNotificationInbox`.
import { defineStore } from "pinia";
import type { NotificationSchema } from "@/__generated__";
import type {
NotificationCreatePayload,
NotificationSchema,
} from "@/__generated__";
import notificationApi from "@/services/api/notification";
// `null` stands for every notification, as it does in the API.
@@ -25,9 +28,21 @@ export default defineStore("v2NotificationInbox", {
this.loaded = true;
},
receive(notification: NotificationSchema) {
if (this.notifications.some((n) => n.id === notification.id)) return;
/** Adds a notification; false when it was already here. */
receive(notification: NotificationSchema): boolean {
if (this.notifications.some((n) => n.id === notification.id)) {
return false;
}
this.notifications = [notification, ...this.notifications];
return true;
},
/** Notifies the signed-in user and returns what was stored. */
async send(
payload: Omit<NotificationCreatePayload, "recipients">,
): Promise<NotificationSchema> {
const { data } = await notificationApi.create(payload);
return data[0];
},
applyRead(ids: NotificationIds, readAt = new Date().toISOString()) {

View File

@@ -12,6 +12,10 @@ function notification(
id: 1,
kind,
level: "info",
title: null,
body: null,
link: null,
icon: null,
data,
actor: null,
read_at: null,
@@ -85,10 +89,39 @@ describe("describeNotification", () => {
expect(view.title).toBe("Your role is now Admin");
});
it("shows a custom notification with its own content", () => {
const view = describeNotification({
...notification("argosy.sync_done"),
title: "Sync finished",
body: "12 saves uploaded",
link: "/rom/12",
icon: "mdi-sync",
});
expect(view).toEqual({
icon: "mdi-sync",
title: "Sync finished",
body: "12 saves uploaded",
to: "/rom/12",
toast: true,
});
});
it("never links outside RomM", () => {
const view = describeNotification({
...notification("custom", {}),
title: "Hi",
link: "//evil.example/login",
});
expect(view.to).toBeNull();
});
it("still renders a kind this client doesn't know", () => {
const view = describeNotification(notification("from_the_future"));
expect(view.title).toBe("New notification");
expect(view.icon).toBe("mdi-bell-outline");
expect(view.to).toBeNull();
});
});

View File

@@ -1,5 +1,6 @@
// A stored notification carries its kind and the values behind its text, not
// the text itself, so it reads in the language of whoever opens it.
// RomM's own kinds carry the values behind their text rather than the text, so
// they read in the language of whoever opens them. Any other kind brings its
// own title and body.
import type { RouteLocationRaw } from "vue-router";
import type { NotificationKind, NotificationSchema } from "@/__generated__";
import i18n from "@/locales";
@@ -26,8 +27,23 @@ function count(value: unknown): number {
return typeof value === "number" && Number.isFinite(value) ? value : 0;
}
// The server only stores in-app paths; this keeps a stray one from leaving RomM.
function inAppLink(link: string | null): string | null {
return link?.startsWith("/") && !link.startsWith("//") ? link : null;
}
function ownContent(notification: NotificationSchema): NotificationView {
return {
icon: notification.icon ?? "mdi-bell-outline",
title: notification.title ?? t("notifications.unknown"),
body: notification.body,
to: inAppLink(notification.link),
toast: true,
};
}
const DESCRIBERS: Record<
NotificationKind,
Exclude<NotificationKind, "custom">,
(data: NotificationData) => NotificationView
> = {
scan_completed: (data) => {
@@ -97,21 +113,14 @@ const DESCRIBERS: Record<
},
};
function isKnownKind(kind: string): kind is NotificationKind {
function isTranslatedKind(kind: string): kind is keyof typeof DESCRIBERS {
return Object.hasOwn(DESCRIBERS, kind);
}
export function describeNotification(
notification: NotificationSchema,
): NotificationView {
if (isKnownKind(notification.kind)) {
return DESCRIBERS[notification.kind](notification.data);
}
return {
icon: "mdi-bell-outline",
title: t("notifications.unknown"),
body: null,
to: null,
toast: true,
};
return isTranslatedKind(notification.kind)
? DESCRIBERS[notification.kind](notification.data)
: ownContent(notification);
}

View File

@@ -69,6 +69,10 @@ function notification(
id,
kind: "role_changed",
level: "info",
title: null,
body: null,
link: null,
icon: null,
data: {},
actor: null,
read_at: null,