desktop: Sync the notification count

The backend now tells the frontend whenever the notifications database
changes, which covers notifications the node writes as it fetches as well
as clears by another instance of the app or the `rad` CLI, which have no
node event. The inbox reloads in place, keeping the rows in view where
they are.
This commit is contained in:
Rūdolfs Ošiņš
2026-11-20 19:32:17 +01:00
parent 748f9e9da7
commit 24eddead28
16 changed files with 233 additions and 57 deletions
@@ -43,6 +43,7 @@ pub(crate) fn startup(app: AppHandle) -> Result<Config, Error> {
let cobs_db =
radicle_types::outbound::sqlite::Sqlite::reader(profile.cobs().join(COBS_DB_FILE))?;
crate::notifications::spawn(app.app_handle().clone(), inbox_db.clone());
let inbox_service = domain::inbox::service::Service::new(inbox_db);
let patch_service = domain::patch::service::Service::new(cobs_db.clone());
let issue_service = domain::issue::service::Service::new(cobs_db);
+1
View File
@@ -1,4 +1,5 @@
mod commands;
mod notifications;
mod ref_updates;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -0,0 +1,37 @@
use std::sync::Once;
use std::time::Duration;
use radicle_types::outbound::sqlite::Sqlite;
use tauri::{AppHandle, Emitter};
/// Tells the frontend when another process changes the notifications, such as
/// the `rad` CLI or another instance of the app clearing some. The node's
/// events only cover notifications it adds while fetching.
pub(crate) fn spawn(app: AppHandle, db: Sqlite) {
static WATCHING: Once = Once::new();
WATCHING.call_once(|| {
std::thread::spawn(move || {
let mut last = None;
let mut failing = false;
loop {
match db.data_version() {
Ok(version) => {
if last.is_some_and(|last| last != version) {
let _ = app.emit("notifications_changed", ());
}
last = Some(version);
failing = false;
}
// Logged once until it works again.
Err(e) => {
if !failing {
log::warn!("Not able to watch the notifications: {e}");
}
failing = true;
}
}
std::thread::sleep(Duration::from_secs(2));
}
});
});
}
@@ -22,6 +22,14 @@ pub struct Sqlite {
}
impl Sqlite {
/// A number that changes whenever another connection commits to the
/// database, such as another process on the same profile.
pub fn data_version(&self) -> Result<i64, Error> {
let mut statement = self.db.prepare("PRAGMA data_version")?;
statement.next()?;
Ok(statement.read::<i64, _>(0)?)
}
/// How long to wait for the database lock to be released before failing a read.
const DB_READ_TIMEOUT: time::Duration = time::Duration::from_secs(3);
@@ -318,6 +326,21 @@ mod test {
use super::Sqlite;
#[test]
fn data_version_changes_with_another_connections_writes() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("notifications.db");
let writer = sql::Connection::open(&path).unwrap();
writer.execute("CREATE TABLE t (x INTEGER)").unwrap();
let reader = Sqlite::reader(&path).unwrap();
let before = reader.data_version().unwrap();
assert_eq!(reader.data_version().unwrap(), before);
writer.execute("INSERT INTO t VALUES (1)").unwrap();
assert_ne!(reader.data_version().unwrap(), before);
}
const RID: &str = "rad:z3fpY7nttPPa6MBnAv2DccHzQJnqe";
const NID: &str = "z6MktULudTtAsAhRegYPiZ6631RV3viv12qd4GQF8z1xB22S";
const COMMIT: &str = "52b0a6dfb600be4e8fe61d70ca40cead71fb03a8";
+3 -2
View File
@@ -273,8 +273,9 @@
}
});
// The node writes notifications as it fetches, so its events say when to
// count them again. Without them, the count is polled. Either way it is
// The backend says when the notifications change, whether the node wrote
// them while fetching or another process cleared some. Without the node's
// events, such as in the test backend, the count is polled. Either way it is
// fetched once at start, since events can already be live then, such as
// after the webview reloads.
onMount(() => {
+31 -16
View File
@@ -12,12 +12,12 @@
import ConfirmClear from "@app/components/ConfirmClear.svelte";
import FuzzySearch from "@app/components/FuzzySearch.svelte";
import NotificationsByRepoComponent from "@app/components/NotificationsByRepo.svelte";
import { getScrollViewport } from "@app/components/ScrollArea.svelte";
interface Props {
clearAll: () => Promise<void>;
clearByIds: (ids: string[]) => Promise<void>;
clearByRepo: (rid: string) => Promise<void>;
loadNew: () => Promise<void>;
notificationCount: number | undefined;
notificationsByRepo: NotificationsByRepo[];
showAll: (rid: string) => Promise<void>;
@@ -27,7 +27,6 @@
clearAll,
clearByIds,
clearByRepo,
loadNew,
notificationCount,
notificationsByRepo,
showAll,
@@ -118,11 +117,36 @@
),
);
function loadedNotificationCount() {
return notificationsByRepo.reduce((acc, repo) => {
return acc + repo.count;
}, 0);
}
// Notifications arriving or being cleared elsewhere update the list in
// place. Unless the list is scrolled to the top, keep the first visible row
// where it is, as browsers' scroll anchoring does, so that nothing moves
// under the user's cursor. WebKit doesn't anchor on its own.
const viewport = getScrollViewport();
let anchors: { el: Element; top: number }[] = [];
$effect.pre(() => {
void notificationsByRepo;
const v = viewport();
if (!v || v.scrollTop === 0) {
anchors = [];
return;
}
const viewTop = v.getBoundingClientRect().top;
anchors = [...v.querySelectorAll("[data-inbox-anchor]")]
.map(el => ({ el, top: el.getBoundingClientRect().top }))
.filter(a => a.top >= viewTop);
});
$effect(() => {
void notificationsByRepo;
const v = viewport();
// The first row still shown, since cleared rows are gone.
const anchor = anchors.find(a => a.el.isConnected);
anchors = [];
if (v && anchor) {
v.scrollTop += anchor.el.getBoundingClientRect().top - anchor.top;
}
});
</script>
<style>
@@ -177,15 +201,6 @@
{isFiltering ? matchedTotal : notificationCount}
</span>
</div>
{#if !isFiltering && notificationCount > loadedNotificationCount()}
<div
class="txt-missing txt-body-m-regular global-flex"
style:margin-left="1rem">
<Button variant="naked" onclick={loadNew}>
See {notificationCount - loadedNotificationCount()} new
</Button>
</div>
{/if}
{#if isFiltering && excludedGroupIds.length > 0}
<div
class="txt-missing txt-body-m-regular global-flex"
@@ -112,6 +112,7 @@
role="button"
class:selected
class="notification-teaser"
data-inbox-anchor
onclick={() => {
if (route) {
revealRepoInSidebar(rid);
@@ -76,6 +76,7 @@
<div>
<div
class="header"
data-inbox-anchor
class:txt-missing={hidden}
style:margin-bottom={!hidden ? "1rem" : undefined}>
<span class="txt-body-l-semibold">
@@ -122,7 +123,7 @@
{#if !hidden}
<div class="container">
{#if groupedNotifications.length > 0}
{#each groupedNotifications as notificationGroup}
{#each groupedNotifications as notificationGroup (`${notificationGroup[0].type}:${notificationGroup[0].id}`)}
<NotificationTeaser
{clearByIds}
{rid}
+12
View File
@@ -0,0 +1,12 @@
// Runs loads so that only the latest one's result is applied: one that finishes
// after a later one started is older than what that one will show.
export function latestOnly<T>(
apply: (value: T) => void,
): (load: () => Promise<T>) => Promise<void> {
let generation = 0;
return async load => {
const current = ++generation;
const value = await load();
if (current === generation) apply(value);
};
}
+4
View File
@@ -17,6 +17,8 @@ import {
loadRepoCommits,
loadRepoHome,
} from "@app/views/repo/router";
import { keys } from "@radicle-gui/core/keys";
import { markLoading } from "@radicle-gui/ui/lib/query.svelte";
import { enterRepo } from "@app/lib/cobQueries";
import {
@@ -26,6 +28,7 @@ import {
InvokeError,
} from "@app/lib/invoke";
import { labs } from "@app/lib/labs";
import { queryClient } from "@app/lib/query";
import { repoListScope } from "@app/lib/repoListScope";
interface BootingRoute {
@@ -143,6 +146,7 @@ export async function loadProfile(
}
export async function loadInbox(): Promise<LoadedInboxRoute> {
markLoading(queryClient, keys.notificationList());
const [sidebarData, notificationsByRepo] = await Promise.all([
loadSidebarData(),
invoke<NotificationsByRepo[]>("list_notifications", {
+4 -2
View File
@@ -56,8 +56,6 @@ export function onRefUpdate(update: RefUpdate) {
]);
invalidate([
...affected.filter(key => !isJobs(key)),
// The node writes notifications as it fetches.
keys.notificationCount(),
// The repository list changes when a seeded repository arrives, or when an
// identity update renames one.
...(get(fetchingRepos).includes(update.rid) ||
@@ -101,6 +99,10 @@ export const createEventEmittersOnce = once(async (): Promise<UnlistenFn> => {
nodeEvents.set(event.payload);
}),
listen<RefUpdate>("ref_update", event => onRefUpdate(event.payload)),
// Another process changed the notifications, such as by clearing some.
listen("notifications_changed", () => {
invalidate([keys.notifications()]);
}),
// The backend may have missed events while it wasn't subscribed.
listen("ref_resync", () => {
void queryClient.invalidateQueries();
+3
View File
@@ -28,6 +28,7 @@ export const mappedWrites = [
"seed",
"unseed",
"clean",
"clear_notifications",
];
// The keys a command's write affects, so that the user's own changes show
@@ -80,6 +81,8 @@ export function writtenKeys(
// Cleaning removes other peers' refs, which can change anything shown.
case "clean":
return typeof rid === "string" ? [keys.repo(rid), keys.repos()] : [];
case "clear_notifications":
return [keys.notifications()];
default:
return [];
}
+69 -35
View File
@@ -1,11 +1,18 @@
<script lang="ts">
import type { NotificationsByRepo } from "@bindings/cob/inbox/NotificationsByRepo";
import { keys } from "@radicle-gui/core/keys";
import { onInvalidate } from "@radicle-gui/ui/lib/query.svelte";
import { untrack } from "svelte";
import { nodeEvents } from "@app/lib/events";
import { invoke } from "@app/lib/invoke";
import { latestOnly } from "@app/lib/latestOnly";
import {
notificationCount,
refreshNotificationCount,
} from "@app/lib/notificationCount.svelte";
import { queryClient } from "@app/lib/query";
import type { SidebarData } from "@app/lib/router/definitions";
import InboxList from "@app/components/InboxList.svelte";
@@ -26,52 +33,80 @@
});
async function clearAll() {
try {
await invoke("clear_notifications", { params: { type: "all" } });
} finally {
await refreshNotificationCount();
await loadNotifications();
}
await invoke("clear_notifications", { params: { type: "all" } });
}
async function clearByRepo(rid: string) {
try {
await invoke("clear_notifications", {
params: { type: "repo", content: rid },
});
} finally {
await refreshNotificationCount();
await loadNotifications();
}
await invoke("clear_notifications", {
params: { type: "repo", content: rid },
});
}
async function clearByIds(ids: string[]) {
try {
await invoke("clear_notifications", {
params: { type: "ids", content: ids },
});
} finally {
await refreshNotificationCount();
await loadNotifications();
}
await invoke("clear_notifications", {
params: { type: "ids", content: ids },
});
}
async function loadNotifications() {
notificationsByRepo = await invoke<NotificationsByRepo[]>(
"list_notifications",
{ params: { take: 100 } },
);
// Repos the user expanded with "Show all", which reloads keep expanded.
let expanded: string[] = [];
// Only the latest load applies, so that a reload started before a clear
// can't bring back what the clear removed.
const applyLatest = latestOnly<NotificationsByRepo[]>(list => {
notificationsByRepo = list;
});
function loadNotifications() {
return applyLatest(async () => {
const [list, ...all] = await Promise.all([
invoke<NotificationsByRepo[]>("list_notifications", {
params: { take: 100 },
}),
...expanded.map(rid =>
invoke<NotificationsByRepo[]>("list_notifications", {
params: { repos: [rid], all: true },
}),
),
]);
const full = new Map(all.flat().map(r => [r.rid, r]));
return list.map(r => full.get(r.rid) ?? r);
});
}
async function showAll(rid: string) {
const all = await invoke<NotificationsByRepo[]>("list_notifications", {
params: { repos: [rid], all: true },
});
notificationsByRepo = [
...notificationsByRepo.filter(r => r.rid !== rid),
...all,
];
if (!expanded.includes(rid)) {
expanded = [...expanded, rid];
}
await loadNotifications();
}
function loadedCount() {
return notificationsByRepo.reduce((acc, r) => acc + r.count, 0);
}
// Follow notifications that arrive or are cleared elsewhere, such as by the
// node or another instance of the app. The backend says when they change;
// new activity on an issue or patch already in the inbox leaves the count
// as it is.
// The count is refreshed along with the list, since the one this view was
// loaded with may be older than the list.
onInvalidate(
queryClient,
() => keys.notificationList(),
async () => {
await loadNotifications();
await refreshNotificationCount();
},
);
// Without the backend's events, such as in the test backend, only the
// polled count tells.
$effect(() => {
if ($nodeEvents) return;
const count = notificationCount.value;
if (count !== undefined && count !== untrack(loadedCount)) {
void loadNotifications().catch(console.error);
}
});
</script>
<style>
@@ -117,7 +152,6 @@
{clearAll}
{clearByIds}
{clearByRepo}
loadNew={loadNotifications}
notificationCount={notificationCount.value}
{notificationsByRepo}
{showAll} />
+37
View File
@@ -0,0 +1,37 @@
import { expect, test } from "vitest";
import { latestOnly } from "@app/lib/latestOnly";
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>(res => {
resolve = res;
});
return { promise, resolve };
}
test("a load that finishes after a later one is dropped", async () => {
const applied: string[] = [];
const load = latestOnly<string>(value => applied.push(value));
const older = deferred<string>();
const newer = deferred<string>();
const first = load(() => older.promise);
const second = load(() => newer.promise);
newer.resolve("newer");
await second;
older.resolve("older");
await first;
expect(applied).toEqual(["newer"]);
});
test("loads that finish in order all apply", async () => {
const applied: string[] = [];
const load = latestOnly<string>(value => applied.push(value));
await load(async () => "first");
await load(async () => "second");
expect(applied).toEqual(["first", "second"]);
});
-1
View File
@@ -89,7 +89,6 @@ const outsideCache = [
// notifications, which their views reload themselves.
"add_artifact_location",
"attest_artifact",
"clear_notifications",
"create_board",
"create_or_open_release",
"delete_release",
+5
View File
@@ -40,7 +40,12 @@ export const keys = {
boards: (rid: string) => ["repo", rid, "boards"] as const,
jobs: (rid: string) => ["repo", rid, "jobs"] as const,
repos: () => ["repos"] as const,
// The repository list for one scope, with the seeded repositories that
// haven't arrived yet.
repoList: (scope: string) => ["repos", scope] as const,
notifications: () => ["notifications"] as const,
notificationCount: () => ["notifications", "count"] as const,
notificationList: () => ["notifications", "list"] as const,
};
// Lists of CI jobs, which scanning every job COB of a repository builds.