desktop: Stop losing and wasting refreshes on events

An update that arrived while a route was still loading was lost, since the
loader's result then counted as fresh, so the events now invalidate through
the shared helper that marks such fetches stale. A repo arriving or renamed
without the update naming its refs left the sidebar list as it was, and
updates that changed nothing still dropped the hover caches.

A test now checks the frontend's ref update type against the generated
one.
This commit is contained in:
Rūdolfs Ošiņš
2026-11-20 19:32:17 +01:00
parent 180ab75364
commit 05d1a99fef
3 changed files with 153 additions and 46 deletions
+26 -30
View File
@@ -2,8 +2,9 @@ import type { Key } from "@radicle-gui/core/keys";
import type { RefUpdate } from "@radicle-gui/core/refUpdates";
import type { UnlistenFn } from "@tauri-apps/api/event";
import { keys } from "@radicle-gui/core/keys";
import { isJobsKey, isRepoInfoKey, keys } from "@radicle-gui/core/keys";
import { affectedKeys } from "@radicle-gui/core/refUpdates";
import { invalidate } from "@radicle-gui/ui/lib/query.svelte";
import { listen } from "@tauri-apps/api/event";
import once from "lodash/once";
import { get } from "svelte/store";
@@ -22,6 +23,7 @@ export function batch(delay: number, jobs: boolean): (affected: Key[]) => void {
const pending = new Map<string, Key>();
let flush: ReturnType<typeof setTimeout> | undefined;
return affected => {
if (affected.length === 0) return;
for (const key of affected) pending.set(key.join("\0"), key);
flush ??= setTimeout(() => {
flush = undefined;
@@ -29,9 +31,9 @@ export function batch(delay: number, jobs: boolean): (affected: Key[]) => void {
pending.clear();
if (!jobs) clearEntityCaches();
for (const queryKey of queryKeys) {
void queryClient.invalidateQueries({
void invalidate(queryClient, {
queryKey,
predicate: query => jobs || !isJobs(query.queryKey as Key),
predicate: query => jobs || !isJobsKey(query.queryKey as Key),
});
}
}, delay);
@@ -39,25 +41,20 @@ export function batch(delay: number, jobs: boolean): (affected: Key[]) => void {
}
// A fetch often updates many refs in a burst, so invalidations are batched.
const invalidate = batch(100, false);
const invalidateBatched = batch(100, false);
// Listing CI jobs scans every job in the repository, and a running
// job updates often, so job lists refresh at most every few seconds.
const invalidateJobs = batch(5_000, true);
function isRepoInfo(key: Key): boolean {
return key[0] === "repo" && key[2] === "info";
}
function isJobs(key: Key): boolean {
return key[0] === "repo" && key[2] === "jobs";
}
// Whether the repository list has `rid` as seeded but not yet arrived.
function underway(rid: string): boolean {
// Whether the repository list shows `rid` as arrived.
function listed(rid: string): boolean {
const list = queryClient.getQueryData<RepoList>(
keys.repoList(repoListScope.value),
);
return (
queryClient
.getQueryData<RepoList>(keys.repoList(repoListScope.value))
?.seededNotReplicated.includes(rid) ?? false
list !== undefined &&
list.repos.some(repo => repo.rid === rid) &&
!list.seededNotReplicated.includes(rid)
);
}
@@ -66,14 +63,15 @@ export function onRefUpdate(update: RefUpdate) {
// A key for the whole repository covers its jobs too.
const repoWide = affected.some(key => key.length === 2 && key[0] === "repo");
invalidateJobs([
...affected.filter(isJobs),
...affected.filter(isJobsKey),
...(repoWide ? [keys.jobs(update.rid)] : []),
]);
invalidate([
...affected.filter(key => !isJobs(key)),
invalidateBatched([
...affected.filter(key => !isJobsKey(key)),
// The repository list changes when a seeded repository arrives, or when an
// identity update renames one.
...(underway(update.rid) ||
...(repoWide ||
!listed(update.rid) ||
update.refs?.some(ref => ref.endsWith("refs/rad/id"))
? [keys.repos()]
: []),
@@ -116,20 +114,18 @@ export const createEventEmittersOnce = once(async (): Promise<UnlistenFn> => {
listen<RefUpdate>("ref_update", event => onRefUpdate(event.payload)),
// Another process changed the notifications, such as by clearing some.
listen("notifications_changed", () => {
invalidate([keys.notifications()]);
invalidateBatched([keys.notifications()]);
}),
// Seeding or unseeding with the `rad` CLI or another instance of the app
// changes the repository list and each repository's seeded state.
listen("policies_changed", () => {
invalidate([keys.repos()]);
void queryClient.invalidateQueries({
predicate: query => isRepoInfo(query.queryKey as Key),
invalidateBatched([keys.repos()]);
void invalidate(queryClient, {
predicate: query => isRepoInfoKey(query.queryKey as Key),
});
}),
// The backend may have missed events while it wasn't subscribed.
listen("ref_resync", () => {
clearEntityCaches();
void queryClient.invalidateQueries();
void invalidate(queryClient);
}),
]);
@@ -139,8 +135,8 @@ export const createEventEmittersOnce = once(async (): Promise<UnlistenFn> => {
const onFocus = () => {
if (!get(nodeEvents)) {
clearEntityCaches();
void queryClient.invalidateQueries({
predicate: query => !isJobs(query.queryKey as Key),
void invalidate(queryClient, {
predicate: query => !isJobsKey(query.queryKey as Key),
});
}
};
+85 -16
View File
@@ -1,26 +1,41 @@
import type { Query } from "@tanstack/query-core";
import type { RefUpdate as BackendRefUpdate } from "@bindings/repo/RefUpdate";
import type { RefUpdate } from "@radicle-gui/core/refUpdates";
import { keys } from "@radicle-gui/core/keys";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
afterEach,
beforeEach,
describe,
expect,
expectTypeOf,
test,
vi,
} from "vitest";
import { queryClient } from "@app/lib/query";
import { repoListScope } from "@app/lib/repoListScope";
import { batch, onRefUpdate } from "@app/lib/startup.svelte";
const { invalidateQueries, clearEntityCaches } = vi.hoisted(() => ({
invalidateQueries: vi.fn(),
const { clearEntityCaches } = vi.hoisted(() => ({
clearEntityCaches: vi.fn(),
}));
vi.mock("@app/lib/query", () => ({
queryClient: { invalidateQueries, getQueryData: vi.fn() },
}));
vi.mock("@app/lib/query", async () => {
const { createQueryClient } =
await import("@radicle-gui/ui/lib/query.svelte");
return { queryClient: createQueryClient() };
});
vi.mock("@app/lib/invoke", () => ({ clearEntityCaches, invoke: vi.fn() }));
vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn() }));
const invalidateQueries = vi.spyOn(queryClient, "invalidateQueries");
const rid = "rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5";
const nid = "z6MkkfM3tPXNPrPevKr3uSiQtHPuwnNhu2yUVjgd2jXVsVz5";
// Whether an invalidation with the given filter refetches a query of `key`.
function covers(call: unknown[], key: readonly unknown[]): boolean {
const { predicate } = call[0] as {
predicate: (query: Pick<Query, "queryKey">) => boolean;
predicate: (query: { queryKey: readonly unknown[] }) => boolean;
};
return predicate({ queryKey: [...key] });
}
@@ -29,7 +44,7 @@ function covers(call: unknown[], key: readonly unknown[]): boolean {
// notification count.
function repoCalls() {
return invalidateQueries.mock.calls.filter(
call => call[0].queryKey[0] === "repo",
call => call[0]?.queryKey?.[0] === "repo",
);
}
@@ -39,8 +54,9 @@ beforeEach(() => {
afterEach(() => {
vi.useRealTimers();
invalidateQueries.mockReset();
invalidateQueries.mockClear();
clearEntityCaches.mockReset();
queryClient.clear();
});
describe("batch", () => {
@@ -52,10 +68,9 @@ describe("batch", () => {
expect(invalidateQueries).not.toHaveBeenCalled();
vi.advanceTimersByTime(100);
expect(invalidateQueries.mock.calls.map(call => call[0].queryKey)).toEqual([
keys.issues(rid),
keys.patches(rid),
]);
expect(invalidateQueries.mock.calls.map(call => call[0]?.queryKey)).toEqual(
[keys.issues(rid), keys.patches(rid)],
);
expect(clearEntityCaches).toHaveBeenCalledTimes(1);
});
@@ -86,13 +101,67 @@ describe("batch", () => {
vi.advanceTimersByTime(100);
const [first] = repoCalls();
expect(first[0].queryKey).toEqual(keys.repo(rid));
expect(first[0]?.queryKey).toEqual(keys.repo(rid));
expect(covers(first, keys.jobs(rid))).toBe(false);
vi.advanceTimersByTime(5_000);
expect(repoCalls().map(call => call[0].queryKey)).toEqual([
expect(repoCalls().map(call => call[0]?.queryKey)).toEqual([
keys.repo(rid),
keys.jobs(rid),
]);
});
test("an empty update neither invalidates nor drops the hover caches", () => {
const invalidate = batch(100, false);
invalidate([]);
vi.advanceTimersByTime(100);
expect(invalidateQueries).not.toHaveBeenCalled();
expect(clearEntityCaches).not.toHaveBeenCalled();
});
});
describe("the repository list", () => {
function listInvalidated(): boolean {
vi.advanceTimersByTime(100);
return invalidateQueries.mock.calls.some(
call => call[0]?.queryKey?.[0] === "repos",
);
}
function list(seededNotReplicated: string[] = []) {
queryClient.setQueryData(keys.repoList(repoListScope.value), {
repos: [{ rid }],
seededNotReplicated,
});
}
test("refreshes for an update naming no refs", () => {
list();
onRefUpdate({ rid });
expect(listInvalidated()).toBe(true);
});
test("refreshes when an identity update may rename a repository", () => {
list();
onRefUpdate({ rid, refs: [`refs/namespaces/${nid}/refs/rad/id`] });
expect(listInvalidated()).toBe(true);
});
test("refreshes when a repository it doesn't show yet arrives", () => {
list([rid]);
onRefUpdate({ rid, refs: [`refs/namespaces/${nid}/refs/heads/main`] });
expect(listInvalidated()).toBe(true);
});
test("stays for a branch update of a listed repository", () => {
list();
onRefUpdate({ rid, refs: [`refs/namespaces/${nid}/refs/heads/main`] });
expect(listInvalidated()).toBe(false);
});
});
test("the core's ref update matches the one the backend sends", () => {
expectTypeOf<RefUpdate>().toEqualTypeOf<BackendRefUpdate>();
});
+42
View File
@@ -0,0 +1,42 @@
import { describe, expect, test } from "vitest";
import { isCobCacheKey, isJobsKey, isRepoInfoKey, keys } from "../src/keys";
const rid = "rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5";
const id = "d87dcfe8c2b3200e78b128d9b959cfdf7063fefe";
describe("key classifiers", () => {
test("job lists", () => {
expect(isJobsKey(keys.jobs(rid))).toBe(true);
expect(isJobsKey(keys.repo(rid))).toBe(false);
expect(isJobsKey(keys.issues(rid))).toBe(false);
});
test("repository info", () => {
expect(isRepoInfoKey(keys.repoInfo(rid))).toBe(true);
expect(isRepoInfoKey(keys.repos())).toBe(false);
});
test("data the COB cache holds", () => {
for (const key of [
keys.repoInfo(rid),
keys.issues(rid),
keys.issueList(rid, "open"),
keys.issue(rid, id),
keys.patches(rid),
keys.patch(rid, id),
]) {
expect(isCobCacheKey(key)).toBe(true);
}
for (const key of [
keys.repo(rid),
keys.code(rid),
keys.jobs(rid),
keys.releases(rid),
keys.boards(rid),
keys.notifications(),
]) {
expect(isCobCacheKey(key)).toBe(false);
}
});
});