desktop: Keep the local actor in the cache

The profile page reloaded its route after every write and only noticed
edits from other devices on navigation. Now writes and the node's
updates refetch the actor in place, like the rest of the cache.
This commit is contained in:
Rūdolfs Ošiņš
2026-11-20 19:32:17 +01:00
parent f87cbcfc94
commit a7c4ded104
14 changed files with 151 additions and 116 deletions
+3 -1
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import type { RepoInfo } from "@bindings/repo/RepoInfo";
import { createActor } from "@app/views/profile/actor";
import { keys } from "@radicle-gui/core/keys";
import { onInvalidate } from "@radicle-gui/ui/lib/query.svelte";
import { getCurrentWindow } from "@tauri-apps/api/window";
@@ -57,6 +58,7 @@
}
const { sidebarData, activeRepo = undefined }: Props = $props();
const current = createActor(() => sidebarData);
const COLLAPSE_MS = 200;
@@ -648,7 +650,7 @@
{#if !mini}
<IdentityButton
config={sidebarData.config}
actor={sidebarData.actor} />
actor={current.actor} />
{/if}
<a
+8
View File
@@ -1,3 +1,4 @@
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { Action as IssueAction } from "@bindings/cob/issue/Action";
import type { Issue } from "@bindings/cob/issue/Issue";
import type { Operation } from "@bindings/cob/Operation";
@@ -37,6 +38,13 @@ export function repoList(scope: string): QueryOptions<RepoList> {
};
}
export function localActor(): QueryOptions<ActorInfo | null> {
return {
queryKey: keys.actor(),
queryFn: () => invoke<ActorInfo | null>("actor"),
};
}
export function releaseCounts(rid: string): QueryOptions<ReleaseCounts> {
return {
queryKey: keys.releaseCount(rid),
-19
View File
@@ -1,4 +1,3 @@
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { AliasSuggestion } from "@bindings/cob/AliasSuggestion";
import type { DiffOptions } from "@bindings/cob/DiffOptions";
import type { Issue } from "@bindings/cob/issue/Issue";
@@ -14,7 +13,6 @@ import type { Job } from "@bindings/repo/Job";
import type { RepoInfo } from "@bindings/repo/RepoInfo";
import type { TreePath } from "@bindings/repo/TreePath";
import { keys } from "@radicle-gui/core/keys";
import { cached } from "@radicle-gui/ui/lib/cached";
import { invalidate } from "@radicle-gui/ui/lib/query.svelte";
import * as tauri from "@tauri-apps/api/core";
@@ -442,23 +440,6 @@ export const cachedGetCommitDiff = cached(
{ max: 100 },
);
/**
* Finding the local actor scans storage like the repo list does, and every
* route loads it while the lab is on, so it is cached with a short TTL; a save
* or create clears it through invalidateReposSummary().
*/
export const cachedActor = cached(
() => invoke<ActorInfo | null>("actor"),
() => "actor",
{ max: 1, ttl: 30_000 },
);
// The sidebar loads the repositories and the actor together, so both go.
export function invalidateReposSummary(): void {
cachedActor.clear();
void queryClient.invalidateQueries({ queryKey: keys.repos() });
}
export async function writeToClipboard(
text: string,
opts?: {
+3 -3
View File
@@ -20,8 +20,8 @@ import {
import { keys } from "@radicle-gui/core/keys";
import { markLoading } from "@radicle-gui/ui/lib/query.svelte";
import { enterRepo, repoList } from "@app/lib/cobQueries";
import { cachedActor, invoke, InvokeError } from "@app/lib/invoke";
import { enterRepo, localActor, repoList } from "@app/lib/cobQueries";
import { invoke, InvokeError } from "@app/lib/invoke";
import { labs } from "@app/lib/labs";
import { projectsOf } from "@app/lib/projects";
import { queryClient } from "@app/lib/query";
@@ -121,7 +121,7 @@ export async function loadSidebarData(): Promise<SidebarData> {
// allowed to stop a route from loading.
async function loadActor(): Promise<Pick<SidebarData, "actor" | "actorError">> {
try {
return { actor: await cachedActor() };
return { actor: await queryClient.fetchQuery(localActor()) };
} catch (error) {
if (error instanceof InvokeError) {
return {
+9 -4
View File
@@ -1,3 +1,4 @@
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { Key } from "@radicle-gui/core/keys";
import type { RefUpdate } from "@radicle-gui/core/refUpdates";
import type { UnlistenFn } from "@tauri-apps/api/event";
@@ -73,14 +74,18 @@ export function onRefUpdate(update: RefUpdate) {
...affected.filter(isJobsKey),
...(repoWide ? [keys.jobs(update.rid)] : []),
]);
const identityMoved =
repoWide || update.refs?.some(ref => ref.endsWith("refs/rad/id"));
invalidateBatched([
...affected.filter(key => !isJobsKey(key)),
// The repository list changes when a seeded repository arrives, or when an
// identity update renames one.
...(repoWide ||
!listed(update.rid) ||
update.refs?.some(ref => ref.endsWith("refs/rad/id"))
? [keys.repos()]
...(identityMoved || !listed(update.rid) ? [keys.repos()] : []),
// The actor's profile and keys live in its repository, and any identity
// update may add this device's key to an actor, as an approved join does.
...(identityMoved ||
queryClient.getQueryData<ActorInfo | null>(keys.actor())?.rid === update.rid
? [keys.actor()]
: []),
]);
}
+19
View File
@@ -12,6 +12,20 @@ interface WriteArgs {
args?: { rid?: unknown };
}
// Each actor write changes the local actor; creating one also adds a
// repository.
const actorWrites = [
"update_actor_profile",
"approve_enrollment",
"approve_actor_revision",
"withdraw_actor_revision",
"reject_actor_revision",
"remove_actor_key",
"leave_actor",
"cancel_leave",
"retire_actor",
];
const releaseWrites = [
"create_or_open_release",
"delete_release",
@@ -41,6 +55,8 @@ export const mappedWrites = [
"unseed",
"clean",
"clear_notifications",
"create_actor",
...actorWrites,
...releaseWrites,
];
@@ -96,7 +112,10 @@ export function writtenKeys(
return typeof rid === "string" ? [keys.repo(rid), keys.repos()] : [];
case "clear_notifications":
return [keys.notifications()];
case "create_actor":
return [keys.repos(), keys.actor()];
default:
if (actorWrites.includes(cmd)) return [keys.actor()];
return releaseWrites.includes(cmd) && typeof rid === "string"
? [keys.releases(rid)]
: [];
+12 -19
View File
@@ -1,7 +1,8 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import { createQuery } from "@radicle-gui/ui/lib/query.svelte";
import { keys } from "@radicle-gui/core/keys";
import { createQuery, invalidate } from "@radicle-gui/ui/lib/query.svelte";
import { untrack } from "svelte";
import { repoList } from "@app/lib/cobQueries";
@@ -20,13 +21,7 @@
import Spinner from "@app/components/Spinner.svelte";
import TextInput from "@app/components/TextInput.svelte";
import {
describeActorError,
keyKind,
profileName,
reload,
roleText,
} from "./actor";
import { describeActorError, keyKind, profileName, roleText } from "./actor";
import KeyChunks from "./KeyChunks.svelte";
import Notice from "./Notice.svelte";
@@ -248,24 +243,22 @@
}
async function done() {
await reload("profile");
await invalidate(queryClient, { queryKey: keys.actor() });
oncancel();
}
// While the code waits to be approved, the page looks every few seconds
// for this key in a profile and moves on once it is.
// While the code waits to be approved, the profile page shows the profile
// as soon as the cache finds this key in one. The node's update of the
// profile's identity usually tells it, but an approval need not move the
// refs it watches, so the page also looks every few seconds.
const APPROVAL_POLL_MS = 5000;
$effect(() => {
if (code === undefined) return;
return poll(async active => {
try {
const actor = await invoke<ActorInfo | null>("actor");
if (active() && actor) void reload("profile");
} catch (e) {
console.warn("Could not look for the approval", e);
}
}, APPROVAL_POLL_MS);
return poll(
() => invalidate(queryClient, { queryKey: keys.actor() }),
APPROVAL_POLL_MS,
);
});
</script>
+5 -5
View File
@@ -95,7 +95,7 @@
revokeError = undefined;
try {
await change(write, "keys");
await change(write);
} catch (error) {
if (onerror) onerror(error);
else
@@ -140,10 +140,10 @@
rid: actor.rid,
majority: actor.majority,
confirm: (code: string, controller: boolean) =>
change(
{ command: "approve_enrollment", args: { code, controller } },
"keys",
),
change({
command: "approve_enrollment",
args: { code, controller },
}),
},
});
}
+6 -4
View File
@@ -12,6 +12,7 @@
import Topbar from "@app/components/Topbar.svelte";
import Layout from "@app/views/repo/Layout.svelte";
import { createActor } from "./actor";
import JoinActor from "./JoinActor.svelte";
import Keys from "./Keys.svelte";
import Notice from "./Notice.svelte";
@@ -24,7 +25,8 @@
}
const { sidebarData, tab }: Props = $props();
const actor = $derived(sidebarData.actor);
const current = createActor(() => sidebarData);
const actor = $derived(current.actor);
const localDid = $derived(didFromPublicKey(sidebarData.config.publicKey));
const tabs = $derived<
@@ -148,7 +150,7 @@
{#if error.code === "ActorError.Ambiguous"}
<ScrollArea style="height: 100%; min-width: 0;">
<div class="inner">
<SeveralProfiles {localDid} {tab} message={error.message} />
<SeveralProfiles {localDid} message={error.message} />
</div>
</ScrollArea>
{:else}
@@ -215,8 +217,8 @@
</Topbar>
<div class="body">
{#if sidebarData.actorError}
{@render failed(sidebarData.actorError)}
{#if current.actorError}
{@render failed(current.actorError)}
{:else if tab === "profile"}
{#if actor || editing}
<ScrollArea style="height: 100%; min-width: 0;">
+10 -13
View File
@@ -117,8 +117,8 @@
const shown = $derived(actor?.profile);
const shownHead = $derived(actor?.head);
// The parent reuses this component across routes, so the form is rebuilt
// when the route brings a different profile, as after a save.
// The actor comes from the cache and changes in place, so the form is
// rebuilt when a different profile head arrives, as after a save.
// svelte-ignore state_referenced_locally
let form = $state<Form>(formFrom(actor?.profile));
@@ -391,19 +391,16 @@
const updating = actor !== null;
try {
await change(
{
command: updating ? "update_actor_profile" : "create_actor",
args: {
profile: profileFrom(form),
images: {
avatar: picked.avatar?.base64,
banner: picked.banner?.base64,
},
await change({
command: updating ? "update_actor_profile" : "create_actor",
args: {
profile: profileFrom(form),
images: {
avatar: picked.avatar?.base64,
banner: picked.banner?.base64,
},
},
"profile",
);
});
} catch (error) {
submitError = describeActorError(
error,
@@ -3,7 +3,6 @@
import { invoke } from "@app/lib/invoke";
import { show } from "@app/lib/modal";
import type { ProfileTab } from "@app/lib/router/definitions";
import Button from "@app/components/Button.svelte";
import CopyableId from "@app/components/CopyableId.svelte";
@@ -23,12 +22,11 @@
interface Props {
localDid: string;
tab: ProfileTab;
// What the backend said when it found the key in several profiles.
message: string;
}
const { localDid, tab, message }: Props = $props();
const { localDid, message }: Props = $props();
let actors = $state<ActorInfo[]>();
let loadError = $state<string>();
@@ -81,13 +79,13 @@
others: actor.keys.length - 1,
confirm: async () => {
try {
await change(
{ command: "retire_actor", args: { rid: actor.rid } },
tab,
);
await change({
command: "retire_actor",
args: { rid: actor.rid },
});
} finally {
// Not waited for: the page has reloaded by now, and this only
// refreshes the list where the device is still in several.
// Not waited for: this only refreshes the list where the device
// is still in several.
void load();
}
},
@@ -105,7 +103,7 @@
acting = true;
try {
await change({ command, args: { rid: actor.rid } }, tab);
await change({ command, args: { rid: actor.rid } });
} catch (e) {
actionError = {
rid: actor.rid,
+63 -24
View File
@@ -3,13 +3,18 @@ import type { ActorKey } from "@bindings/actor/ActorKey";
import type { ActorProfile } from "@bindings/actor/ActorProfile";
import type { ActorRevision } from "@bindings/actor/ActorRevision";
import type { ProfileImages } from "@bindings/actor/ProfileImages";
import type { Key } from "@radicle-gui/core/keys";
import { isJobsKey, keys } from "@radicle-gui/core/keys";
import { createQuery, invalidate } from "@radicle-gui/ui/lib/query.svelte";
import { get } from "svelte/store";
import { localActor } from "@app/lib/cobQueries";
import { nodeRunning } from "@app/lib/events";
import { invalidateReposSummary, invoke, InvokeError } from "@app/lib/invoke";
import * as router from "@app/lib/router";
import type { ProfileTab } from "@app/lib/router/definitions";
import { invoke, InvokeError } from "@app/lib/invoke";
import { labs } from "@app/lib/labs";
import { queryClient } from "@app/lib/query";
import type { SidebarData } from "@app/lib/router/definitions";
import { formatTimestamp, publicKeyFromDid, truncateId } from "@app/lib/utils";
import { announce } from "@app/components/AnnounceSwitch.svelte";
@@ -32,11 +37,41 @@ export function describeActorError(
return error instanceof Error ? error.message : fallback;
}
// Reloads the profile page on `tab` from storage, so it shows what was
// written.
export async function reload(tab: ProfileTab): Promise<void> {
invalidateReposSummary();
await router.replace({ resource: "profile", tab });
// The local actor as the cache has it, so that writes and the node's updates
// show in place, and as the route loaded it until the cache has an answer.
// Create it during component initialisation.
export function createActor(
loaded: () => Pick<SidebarData, "actor" | "actorError">,
): Pick<SidebarData, "actor" | "actorError"> {
const query = createQuery(queryClient, () => ({
...localActor(),
enabled: labs.actorRepos,
}));
// The query's own error, when it has one the page can show.
const queryError = () => {
const { error } = query.current;
return error instanceof InvokeError
? { code: error.code, message: error.message }
: undefined;
};
// A disabled query still holds what it last fetched, so with the lab off
// the route's values count.
return {
get actor() {
if (!labs.actorRepos) return loaded().actor;
const { data } = query.current;
if (queryError()) return null;
return data !== undefined ? data : loaded().actor;
},
get actorError() {
if (!labs.actorRepos) return loaded().actorError;
const error = queryError();
if (error) return error;
return query.current.data !== undefined ? undefined : loaded().actorError;
},
};
}
// The actor writes and what each takes; the options are added by `change`.
@@ -60,26 +95,30 @@ export type ActorWrite =
// The votes on an open identity change.
export type Vote = Extract<ActorWrite, { args: { id: string } }>["command"];
// Runs an actor write, then reloads `tab` whether or not it went through: a
// failure may come from state the page has not seen, and a write that went
// through is not undone by a reload that did not. The write announces when
// the node runs and the user has not turned announcing off.
export async function change(
{ command, args }: ActorWrite,
tab: ProfileTab,
): Promise<void> {
// Runs an actor write, which announces when the node runs and the user has
// not turned announcing off. It returns once the actor is refetched, whether
// or not the write went through, so callers see what it left. The actor's
// repository is refetched too, since its identity and code change; most
// writes don't name it, so it comes from the cache.
export async function change({ command, args }: ActorWrite): Promise<void> {
const opts = { announce: get(nodeRunning) && get(announce) };
const reloadQuietly = () =>
reload(tab).catch((e: unknown) =>
console.warn("Could not reload the profile", e),
);
const rid =
"rid" in args
? args.rid
: queryClient.getQueryData<ActorInfo | null>(keys.actor())?.rid;
try {
await invoke<ActorInfo>(command, { ...args, opts });
} catch (error) {
await reloadQuietly();
throw error;
} finally {
await Promise.all([
invalidate(queryClient, { queryKey: keys.actor() }),
rid !== undefined &&
invalidate(queryClient, {
queryKey: keys.repo(rid),
// Job lists don't depend on the identity, and listing them is slow.
predicate: query => !isJobsKey(query.queryKey as Key),
}),
]);
}
await reloadQuietly();
}
// The keys that govern the actor's identity.
+3 -14
View File
@@ -72,24 +72,13 @@ const outsideCache = [
"pick_artifact_directory",
"pick_artifact_files",
"startup",
// Actor writes, after which the profile page reloads itself. A join code
// only changes the actor once another device approves it.
"approve_actor_revision",
"approve_enrollment",
"cancel_leave",
"create_actor",
"join_actor",
"leave_actor",
"reject_actor_revision",
"remove_actor_key",
"retire_actor",
"update_actor_profile",
"withdraw_actor_revision",
// Writes outside the cache. The board shows its own writes as they land,
// and a reload after each would make cards jump while the user moves more.
// Artifact seeding, embeds and files aren't in the cache.
// Artifact seeding, embeds and files aren't in the cache. A join code only
// changes the actor once another device approves it.
"create_board",
"download_artifact",
"join_actor",
"rename_board",
"save_diff_to_disk",
"save_embed_by_bytes",
+2
View File
@@ -34,6 +34,8 @@ export const keys = {
// The repository list for one scope, with the seeded repositories that
// haven't arrived yet.
repoList: (scope: string) => ["repos", scope] as const,
// The local actor, which is found by scanning every repository's identity.
actor: () => ["actor"] as const,
notifications: () => ["notifications"] as const,
notificationCount: () => ["notifications", "count"] as const,
notificationList: () => ["notifications", "list"] as const,