diff --git a/desktop/crates/radicle-tauri/src/commands/startup.rs b/desktop/crates/radicle-tauri/src/commands/startup.rs index f8d673094..2e968387f 100644 --- a/desktop/crates/radicle-tauri/src/commands/startup.rs +++ b/desktop/crates/radicle-tauri/src/commands/startup.rs @@ -1,3 +1,5 @@ +use std::sync::Once; + use tauri::{AppHandle, Emitter, Manager}; use radicle::cob::cache::COBS_DB_FILE; @@ -56,15 +58,27 @@ pub(crate) fn startup(app: AppHandle) -> Result { // Both probes are blocking socket calls, so they get their own thread. The // radicle node's event goes out first, so a slow artifact node can't // delay it. + // Started once per app, as `startup` runs again whenever the webview + // reloads. + static PROBING: Once = Once::new(); let probe_state = state.clone(); - std::thread::spawn(move || { - loop { - let _ = node_handle.emit("node_running", node.is_running()); - let _ = node_handle.emit("artifact_node_running", probe_state.artifact_node_running()); - std::thread::sleep(std::time::Duration::from_secs(2)); - } + PROBING.call_once(|| { + std::thread::spawn(move || { + loop { + let _ = node_handle.emit("node_running", node.is_running()); + let _ = node_handle.emit("node_events", crate::ref_updates::is_live()); + let _ = + node_handle.emit("artifact_node_running", probe_state.artifact_node_running()); + std::thread::sleep(std::time::Duration::from_secs(2)); + } + }); }); + crate::ref_updates::spawn( + app.app_handle().clone(), + Node::new(profile.home().socket_from_env()), + ); + app.manage(state.clone()); Ok(state.config()) diff --git a/desktop/crates/radicle-tauri/src/lib.rs b/desktop/crates/radicle-tauri/src/lib.rs index fae9ed1e0..fd644e6e2 100644 --- a/desktop/crates/radicle-tauri/src/lib.rs +++ b/desktop/crates/radicle-tauri/src/lib.rs @@ -1,4 +1,5 @@ mod commands; +mod ref_updates; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; diff --git a/desktop/crates/radicle-tauri/src/ref_updates.rs b/desktop/crates/radicle-tauri/src/ref_updates.rs new file mode 100644 index 000000000..36ed97d63 --- /dev/null +++ b/desktop/crates/radicle-tauri/src/ref_updates.rs @@ -0,0 +1,87 @@ +use std::sync::Once; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +use radicle::identity::RepoId; +use radicle::node::{self, Event, Handle, Node}; +use radicle::storage; +use tauri::{AppHandle, Emitter}; + +/// Refs that changed in a repository. `refs` is `None` when the node doesn't +/// say which refs changed, such as when the local user pushed. +#[derive(Clone, serde::Serialize)] +struct RefUpdate { + rid: RepoId, + #[serde(skip_serializing_if = "Option::is_none")] + refs: Option>, +} + +/// Whether the subscription to the node's events is up, so the frontend knows +/// whether it can rely on them or has to poll. +static LIVE: AtomicBool = AtomicBool::new(false); + +pub(crate) fn is_live() -> bool { + LIVE.load(Ordering::Relaxed) +} + +/// Starts forwarding the node's ref updates, once per app: `startup` runs again +/// whenever the webview reloads. +pub(crate) fn spawn(app: AppHandle, node: Node) { + static FORWARDING: Once = Once::new(); + FORWARDING.call_once(|| { + std::thread::spawn(move || forward(app, node)); + }); +} + +/// Forwards the node's ref updates to the frontend as `ref_update` events. +/// Every time the subscription (re)starts, the frontend gets `ref_resync`, +/// because it may have missed events in between. +fn forward(app: AppHandle, node: Node) { + loop { + if let Ok(events) = node.subscribe(Duration::from_secs(60 * 60 * 24)) { + LIVE.store(true, Ordering::Relaxed); + let _ = app.emit("ref_resync", ()); + for event in events { + match event { + Ok(event) => { + if let Some(update) = ref_update(event) { + let _ = app.emit("ref_update", update); + } + } + // An event this version can't read, such as a new kind + // from a newer node, doesn't end the subscription. + Err(node::Error::InvalidJson { .. } | node::Error::Command { .. }) => {} + Err(_) => break, + } + } + } + LIVE.store(false, Ordering::Relaxed); + std::thread::sleep(Duration::from_secs(2)); + } +} + +fn ref_update(event: Event) -> Option { + match event { + Event::RefsFetched { rid, updated, .. } => { + let refs: Vec = updated + .into_iter() + .filter_map(|update| match update { + storage::RefUpdate::Updated { name, .. } + | storage::RefUpdate::Created { name, .. } + | storage::RefUpdate::Deleted { name, .. } => Some(name.to_string()), + storage::RefUpdate::Skipped { .. } => None, + }) + .collect(); + (!refs.is_empty()).then_some(RefUpdate { + rid, + refs: Some(refs), + }) + } + Event::CanonicalRefUpdated { rid, refname, .. } => Some(RefUpdate { + rid, + refs: Some(vec![refname.to_string()]), + }), + Event::LocalRefsAnnounced { rid, .. } => Some(RefUpdate { rid, refs: None }), + _ => None, + } +} diff --git a/desktop/src/App.svelte b/desktop/src/App.svelte index f26a8075b..a1d42e057 100644 --- a/desktop/src/App.svelte +++ b/desktop/src/App.svelte @@ -3,6 +3,7 @@ import type { ErrorWrapper } from "@bindings/error/ErrorWrapper"; import type { RepoInfo } from "@bindings/repo/RepoInfo"; + import { createQuery } from "@radicle-gui/ui/lib/query.svelte"; import { onDestroy, onMount } from "svelte"; import { get } from "svelte/store"; @@ -13,10 +14,12 @@ resetFontSize, } from "@app/lib/appearance.svelte"; import { checkAuth, startup } from "@app/lib/auth.svelte"; + import { repoInfo } from "@app/lib/cobQueries"; import { deepLinksReady, listenForDeepLinks } from "@app/lib/deepLink"; import { dynamicInterval } from "@app/lib/interval"; import { invoke } from "@app/lib/invoke"; import { hide, modalStore, show, toggle } from "@app/lib/modal"; + import { queryClient } from "@app/lib/query"; import * as router from "@app/lib/router"; import { isLoadedRepoRoute } from "@app/lib/router/definitions"; import { listenForShortcuts, useShortcuts } from "@app/lib/shortcuts.svelte"; @@ -62,10 +65,20 @@ const activeRouteStore = router.activeRouteStore; - const activeRepo = $derived.by((): RepoInfo | undefined => { + const loadedRepo = $derived.by((): RepoInfo | undefined => { const route = $activeRouteStore; return isLoadedRepoRoute(route) ? route.params.repo : undefined; }); + // The sidebar's counts follow the cache, which ref updates and the user's + // own writes keep current, instead of staying as the route loaded them. + const activeRepoQuery = createQuery(queryClient, () => ({ + ...repoInfo(loadedRepo?.rid ?? ""), + enabled: loadedRepo !== undefined, + })); + const activeRepo = $derived.by((): RepoInfo | undefined => { + const cached = activeRepoQuery.current.data; + return cached && cached.rid === loadedRepo?.rid ? cached : loadedRepo; + }); function modalHasTextEntry(): boolean { return ( diff --git a/desktop/src/components/AppSidebar.svelte b/desktop/src/components/AppSidebar.svelte index eb9bb6031..1a3d2d3fb 100644 --- a/desktop/src/components/AppSidebar.svelte +++ b/desktop/src/components/AppSidebar.svelte @@ -1,6 +1,8 @@ + + + + +
+ {message} + +
diff --git a/desktop/src/lib/cobQueries.ts b/desktop/src/lib/cobQueries.ts new file mode 100644 index 000000000..a4a23c2f8 --- /dev/null +++ b/desktop/src/lib/cobQueries.ts @@ -0,0 +1,106 @@ +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"; +import type { Action as PatchAction } from "@bindings/cob/patch/Action"; +import type { Patch } from "@bindings/cob/patch/Patch"; +import type { Revision } from "@bindings/cob/patch/Revision"; +import type { Thread } from "@bindings/cob/thread/Thread"; +import type { RepoInfo } from "@bindings/repo/RepoInfo"; +import type { Key } from "@radicle-gui/core/keys"; +import type { QueryOptions } from "@radicle-gui/ui/lib/query.svelte"; + +import { isJobsKey, keys } from "@radicle-gui/core/keys"; +import { get } from "svelte/store"; + +import { nodeEvents } from "@app/lib/events"; +import { invoke } from "@app/lib/invoke"; +import { queryClient } from "@app/lib/query"; + +export function repoInfo(rid: string): QueryOptions { + return { + queryKey: keys.repoInfo(rid), + queryFn: () => invoke("repo_by_id", { rid }), + }; +} + +// `issue` is null once the issue is deleted. +export interface IssueDetail { + issue: Issue | undefined; + activity: Operation[]; + threads: Thread[]; +} + +export function issueDetail( + rid: string, + id: string, +): QueryOptions { + return { + queryKey: keys.issue(rid, id), + queryFn: async () => { + const issue = + (await invoke("issue_by_id", { rid, id })) ?? undefined; + // A deleted issue has no operations left to read. + if (!issue) return { issue, activity: [], threads: [] }; + const [activity, threads] = await Promise.all([ + invoke[]>("activity_by_issue", { rid, id }), + invoke("comment_threads_by_issue_id", { rid, id }), + ]); + return { issue, activity, threads: threads ?? [] }; + }, + }; +} + +// `patch` is undefined once the patch is deleted. +export interface PatchDetail { + patch: Patch | undefined; + revisions: Revision[]; + activity: Operation[]; +} + +export function patchDetail( + rid: string, + id: string, +): QueryOptions { + return { + queryKey: keys.patch(rid, id), + queryFn: async () => { + const patch = + (await invoke("patch_by_id", { rid, id })) ?? undefined; + // A deleted patch has no operations left to read. + if (!patch) return { patch, revisions: [], activity: [] }; + const [revisions, activity] = await Promise.all([ + invoke("revisions_by_patch", { rid, id }), + invoke[]>("activity_by_patch", { rid, id }), + ]); + return { patch, revisions: revisions ?? [], activity }; + }, + }; +} + +// Route loaders load through the cache, so that the view they load starts from +// the cache's data and shares it. While the node runs, its events keep the +// cache current, so a cached entry is reused unless it was invalidated. +// Without its events, loaders always refetch. +export function load(options: QueryOptions): Promise { + return queryClient.fetchQuery({ + ...options, + staleTime: get(nodeEvents) ? Infinity : 0, + }); +} + +let currentRid: string | undefined; + +// Entering a repository refetches its data, so that leaving it and coming back +// recovers from any event the cache missed. Job lists are left out: they only +// change through the node's events, and listing them is slow. +export function enterRepo(rid: string | undefined): void { + if (rid === currentRid) return; + currentRid = rid; + if (rid !== undefined) { + void queryClient.invalidateQueries({ + queryKey: keys.repo(rid), + predicate: query => !isJobsKey(query.queryKey as Key), + refetchType: "none", + }); + } +} diff --git a/desktop/src/lib/events.ts b/desktop/src/lib/events.ts index 5cc207eb4..782a82cb8 100644 --- a/desktop/src/lib/events.ts +++ b/desktop/src/lib/events.ts @@ -1,6 +1,9 @@ import { writable } from "svelte/store"; export const nodeRunning = writable(false); +// Whether the backend is subscribed to the node's events, so that the cache +// can rely on them. Without them, views poll or refetch on navigation. +export const nodeEvents = writable(false); // Undefined until the first probe, so nothing reports the node as down before // it has been asked. export const artifactNodeRunning = writable(undefined); diff --git a/desktop/src/lib/invoke.ts b/desktop/src/lib/invoke.ts index 3524ac502..09c5ba5d2 100644 --- a/desktop/src/lib/invoke.ts +++ b/desktop/src/lib/invoke.ts @@ -15,17 +15,47 @@ import type { RepoInfo } from "@bindings/repo/RepoInfo"; import type { RepoSummary } from "@bindings/repo/RepoSummary"; import type { TreePath } from "@bindings/repo/TreePath"; +import { keys } from "@radicle-gui/core/keys"; import { cached } from "@radicle-gui/ui/lib/cached"; import * as tauri from "@tauri-apps/api/core"; import { labs } from "@app/lib/labs"; import { projectsOf } from "@app/lib/projects"; +import { queryClient } from "@app/lib/query"; import type { RepoListScope } from "@app/lib/repoListScope"; +// Commands that change a repository's info: its issue and patch counts, and +// whether it is seeded. The node doesn't announce the user's own writes when +// announcing is off, so the cache learns of them here. +const countWrites = new Set([ + "create_issue", + "edit_issue", + "delete_issue", + "edit_patch", + "delete_patch", + "rebuild_issue_cache", + "rebuild_patch_cache", + "seed", + "unseed", +]); + export async function invoke( cmd: string, args?: tauri.InvokeArgs, options?: tauri.InvokeOptions, +): Promise { + const result = await invokeCommand(cmd, args, options); + const rid = (args as { rid?: unknown } | undefined)?.rid; + if (countWrites.has(cmd) && typeof rid === "string") { + void queryClient.invalidateQueries({ queryKey: keys.repoInfo(rid) }); + } + return result; +} + +async function invokeCommand( + cmd: string, + args?: tauri.InvokeArgs, + options?: tauri.InvokeOptions, ): Promise { if (import.meta.env.VITE_LOG_INVOKE_TIMINGS === "true") { const start = performance.now(); diff --git a/desktop/src/lib/paginatedList.svelte.ts b/desktop/src/lib/paginatedList.svelte.ts index 7f791ef5c..863fec518 100644 --- a/desktop/src/lib/paginatedList.svelte.ts +++ b/desktop/src/lib/paginatedList.svelte.ts @@ -66,8 +66,9 @@ export function createPaginatedList(opts: PaginatedListOptions) { const abort = async (): Promise => undefined; // Parent reuses the view across filter changes; a key change resets the - // pagination state from the loader's fresh page. - $effect(() => { + // pagination state from the loader's fresh page. Before other effects, so + // that a refresh the view starts for the new key isn't aborted by it. + $effect.pre(() => { const key = opts.key(); const fresh = opts.page(); // Skip the initial mount (state is seeded above, possibly restored); only @@ -89,6 +90,13 @@ export function createPaginatedList(opts: PaginatedListOptions) { async function loadMore(all: boolean = false): Promise { if (!more) return; loadingMore = true; + if (refreshing) { + await refreshing; + if (!more) { + loadingMore = false; + return; + } + } let superseded = false; try { const page = await loader.run(async () => @@ -161,6 +169,54 @@ export function createPaginatedList(opts: PaginatedListOptions) { } } + // Refetches the rows shown after a change elsewhere, such as a new issue. + // The list keeps its last row as its end, so that rows added before the ones + // in view leave them in place, and nothing shows as loading. A page load + // waits for it rather than cancelling it, and one it cancels leaves + // `loadingMore` for it to clear. + let refreshing: Promise | undefined; + let isRefreshing = $state(false); + async function refresh(): Promise { + const interrupted = loadingMore; + const run = (async () => { + const shown = Math.max(items.length, opts.pageSize); + const lastId = + items.length > 0 ? opts.id(items[items.length - 1]) : undefined; + let superseded = false; + try { + const page = await loader.run(async () => + opts.fetchPage(0, shown + opts.pageSize), + ); + if (page === undefined) { + superseded = true; + return; + } + const end = + lastId === undefined + ? -1 + : page.content.findIndex(item => opts.id(item) === lastId); + const keep = end >= 0 ? end + 1 : Math.min(page.content.length, shown); + items = page.content.slice(0, keep); + cursor = keep; + more = page.more || keep < page.content.length; + } catch (error) { + console.error("Refreshing the list failed: ", error); + } finally { + if (interrupted && !superseded) loadingMore = false; + } + })(); + refreshing = run; + isRefreshing = true; + try { + await run; + } finally { + if (refreshing === run) { + refreshing = undefined; + isRefreshing = false; + } + } + } + if (staleWindow !== undefined) { void revalidate(staleWindow); } @@ -200,6 +256,9 @@ export function createPaginatedList(opts: PaginatedListOptions) { get loadingMore() { return loadingMore; }, + get refreshing() { + return isRefreshing; + }, get initialScrollOffset() { return restoredScroll?.scrollOffset; }, @@ -211,6 +270,7 @@ export function createPaginatedList(opts: PaginatedListOptions) { }, loadMore, revalidate, + refresh, persistScroll, }; } diff --git a/desktop/src/lib/query.ts b/desktop/src/lib/query.ts new file mode 100644 index 000000000..e3c248b4a --- /dev/null +++ b/desktop/src/lib/query.ts @@ -0,0 +1,3 @@ +import { createQueryClient } from "@radicle-gui/ui/lib/query.svelte"; + +export const queryClient = createQueryClient(); diff --git a/desktop/src/lib/router/definitions.ts b/desktop/src/lib/router/definitions.ts index 6e3350648..13dec5262 100644 --- a/desktop/src/lib/router/definitions.ts +++ b/desktop/src/lib/router/definitions.ts @@ -18,6 +18,7 @@ import { loadRepoHome, } from "@app/views/repo/router"; +import { enterRepo } from "@app/lib/cobQueries"; import { cachedActor, cachedListReposSummary, @@ -158,6 +159,8 @@ export async function loadRoute( route: Route, previousLoaded: LoadedRoute, ): Promise { + enterRepo("rid" in route ? route.rid : undefined); + if (route.resource === "inbox") { return loadInbox(); } else if (route.resource === "guide") { diff --git a/desktop/src/lib/startup.svelte.ts b/desktop/src/lib/startup.svelte.ts index 651b187e9..db7e0f80a 100644 --- a/desktop/src/lib/startup.svelte.ts +++ b/desktop/src/lib/startup.svelte.ts @@ -1,11 +1,47 @@ +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 { affectedKeys } from "@radicle-gui/core/refUpdates"; import { listen } from "@tauri-apps/api/event"; import once from "lodash/once"; +import { get } from "svelte/store"; import { invoke } from "@app/lib/invoke"; +import { queryClient } from "@app/lib/query"; -import { artifactNodeRunning, nodeRunning } from "./events"; +import { artifactNodeRunning, nodeEvents, nodeRunning } from "./events"; + +// Collects keys and invalidates them together after `delay`. +function batch(delay: number): (affected: Key[]) => void { + // eslint-disable-next-line svelte/prefer-svelte-reactivity -- never rendered + const pending = new Map(); + let flush: ReturnType | undefined; + return affected => { + if (affected.length === 0) return; + for (const key of affected) pending.set(key.join("\0"), key); + flush ??= setTimeout(() => { + flush = undefined; + const queryKeys = [...pending.values()]; + pending.clear(); + for (const queryKey of queryKeys) { + void queryClient.invalidateQueries({ queryKey }); + } + }, delay); + }; +} + +// A fetch often updates many refs in a burst, so invalidations are batched. +const invalidate = batch(100); + +function onRefUpdate(update: RefUpdate) { + invalidate([ + ...affectedKeys(update), + // The node writes notifications as it fetches. + keys.notificationCount(), + ]); +} export let unlistenNodeEvents: UnlistenFn | undefined = undefined; @@ -37,6 +73,27 @@ export const createEventEmittersOnce = once(async (): Promise => { listen("artifact_node_running", event => { artifactNodeRunning.set(event.payload); }), + listen("node_events", event => { + nodeEvents.set(event.payload); + }), + listen("ref_update", event => onRefUpdate(event.payload)), + // The backend may have missed events while it wasn't subscribed. + listen("ref_resync", () => { + void queryClient.invalidateQueries(); + }), ]); - return () => unlisteners.forEach(unlisten => unlisten()); + + // Without the node's events, refetch what is shown whenever the user comes + // back to the window. + const onFocus = () => { + if (!get(nodeEvents)) { + void queryClient.invalidateQueries(); + } + }; + window.addEventListener("focus", onFocus); + + return () => { + unlisteners.forEach(unlisten => unlisten()); + window.removeEventListener("focus", onFocus); + }; }); diff --git a/desktop/src/views/repo/Issue.svelte b/desktop/src/views/repo/Issue.svelte index d1c67214d..d04b2cebd 100644 --- a/desktop/src/views/repo/Issue.svelte +++ b/desktop/src/views/repo/Issue.svelte @@ -8,10 +8,14 @@ import type { Config } from "@bindings/config/Config"; import type { RepoInfo } from "@bindings/repo/RepoInfo"; + import { createQuery, pinned } from "@radicle-gui/ui/lib/query.svelte"; + + import { issueDetail } from "@app/lib/cobQueries"; import { nodeRunning } from "@app/lib/events"; import { invoke } from "@app/lib/invoke"; import { issueTimeline } from "@app/lib/issueTimeline"; import { show } from "@app/lib/modal"; + import { queryClient } from "@app/lib/query"; import * as roles from "@app/lib/roles"; import * as router from "@app/lib/router"; import { @@ -32,6 +36,7 @@ import IssueDescription from "@app/components/IssueDescription.svelte"; import IssueMetadata from "@app/components/IssueMetadata.svelte"; import IssueStateButton from "@app/components/IssueStateButton.svelte"; + import NewerBanner from "@app/components/NewerBanner.svelte"; import ScrollArea from "@app/components/ScrollArea.svelte"; import ShareButton from "@app/components/ShareButton.svelte"; import Topbar from "@app/components/Topbar.svelte"; @@ -47,9 +52,48 @@ threads: Thread[]; } - /* eslint-disable prefer-const */ - let { repo, issue, activity, config, threads }: Props = $props(); - /* eslint-enable prefer-const */ + const { + repo, + issue: loadedIssue, + activity: loadedActivity, + config, + threads: loadedThreads, + }: Props = $props(); + + // The route loader already put the issue in the cache. + const query = $derived(issueDetail(repo.rid, loadedIssue.id)); + const detail = createQuery(queryClient, () => query); + + const issue = $derived(detail.current.data?.issue ?? loadedIssue); + + // Deleted elsewhere while shown, so there is nothing left to show. Deleting + // it here navigates by itself. + let deleting = false; + $effect(() => { + if (detail.current.data && !detail.current.data.issue && !deleting) { + void router.push({ + resource: "repo.issues", + rid: repo.rid, + status: loadedIssue.state.status, + }); + } + }); + const activity = $derived(detail.current.data?.activity ?? loadedActivity); + const threads = $derived(detail.current.data?.threads ?? loadedThreads); + + const noEdits: NonNullable["edits"] = []; + // The description is what the user reads, so an edit by someone else + // doesn't replace it until the user asks for it. Reactions show as they + // arrive. + const description = pinned(() => issue.body?.edits ?? noEdits); + // svelte-ignore state_referenced_locally + let pinnedIssueId = loadedIssue.id; + $effect.pre(() => { + if (loadedIssue.id !== pinnedIssueId) { + pinnedIssueId = loadedIssue.id; + description.apply(); + } + }); const canEditIssue = $derived( roles.isDelegateOrAuthor( @@ -65,21 +109,13 @@ const activityItems = $derived(issueTimeline(issue, activity)); + // After the user's own changes, refetch and show them right away. async function reload() { - [issue, activity, threads] = await Promise.all([ - invoke("issue_by_id", { - rid: repo.rid, - id: issue.id, - }), - invoke[]>("activity_by_issue", { - rid: repo.rid, - id: issue.id, - }), - invoke("comment_threads_by_issue_id", { - rid: repo.rid, - id: issue.id, - }), - ]); + await queryClient.invalidateQueries({ + queryKey: query.queryKey, + refetchType: "all", + }); + description.apply(); } async function createComment( @@ -199,6 +235,7 @@ status: issue.state.status, }); } catch (error) { + deleting = false; console.error("Deleting issue failed", error); } } @@ -348,11 +385,17 @@
- {#if issue.body} + {#if description.stale} + description.apply()} /> + {/if} + {#if issue.body && description.current.length > 0} {@const body = issue.body} repoInfo(loadedRepo.rid)); + const repo = $derived(repoQuery.current.data ?? loadedRepo); function listKey(filter: IssueStatus): string { return `repo.issues:${repo.rid}:${filter}`; @@ -81,8 +87,15 @@ $effect(() => { // Only record counts from settled, fresh data: while a history-restore // revalidation is in flight (loadingMore), the snapshot's length/more are - // stale and would flag a cache mismatch that isn't there. - if (list.more === false && !list.loadingMore) { + // stale and would flag a cache mismatch that isn't there. An update + // refreshes the list and the repo's counts separately, so one of them + // can briefly be ahead of the other. + if ( + list.more === false && + !list.loadingMore && + !list.refreshing && + !repoQuery.current.isFetching + ) { updateIssueCounts( list.items.length, { @@ -125,14 +138,13 @@ const contextMenu = createListContextMenu(() => list.items); async function refresh() { - // Re-fetch the repo too: the tab counts come from its project payload. - const [repoInfo] = await Promise.all([ - invoke("repo_by_id", { rid: repo.rid }), - list.revalidate(Math.max(list.items.length, DEFAULT_TAKE)), - ]); - repo = repoInfo; + await list.refresh(); } + // The paginated list keeps its own pages, so the cache only tells + // it when to refresh. + onInvalidate(queryClient, () => keys.issueList(repo.rid, status), refresh); + const searchResults = $derived( searchCobs(debouncedSearch.current, list.items), ); diff --git a/desktop/src/views/repo/Patch.svelte b/desktop/src/views/repo/Patch.svelte index 95fa0fb38..c9ddb95cf 100644 --- a/desktop/src/views/repo/Patch.svelte +++ b/desktop/src/views/repo/Patch.svelte @@ -12,10 +12,12 @@ import type { RepoInfo } from "@bindings/repo/RepoInfo"; import UserAvatar from "@radicle-gui/ui/components/UserAvatar.svelte"; + import { createQuery } from "@radicle-gui/ui/lib/query.svelte"; import countBy from "lodash/countBy"; import { tick } from "svelte"; import { SvelteSet } from "svelte/reactivity"; + import { patchDetail } from "@app/lib/cobQueries"; import { commentSourcesOf } from "@app/lib/commentSources"; import { checkedFileProgress } from "@app/lib/diffText"; import { draftReviewStorage } from "@app/lib/draftReviewStorage"; @@ -30,6 +32,7 @@ import { scrollBehavior } from "@app/lib/motion"; import { setPatchActivitySource } from "@app/lib/patchActivityContext"; import { patchContributions } from "@app/lib/patchContributions"; + import { queryClient } from "@app/lib/query"; import type { ReviewEntry } from "@app/lib/reviewSummary"; import { compareRange, revisionRange } from "@app/lib/revisionCompare"; import { revisionTitle } from "@app/lib/revisionDescription"; @@ -82,18 +85,40 @@ review?: Review; } - /* eslint-disable prefer-const */ - let { + const { repo, - patch, - revisions, + patch: loadedPatch, + revisions: loadedRevisions, config, - activity, + activity: loadedActivity, status, view, review, }: Props = $props(); - /* eslint-enable prefer-const */ + + // The route loader already put the patch in the cache. + const query = $derived(patchDetail(repo.rid, loadedPatch.id)); + const detail = createQuery(queryClient, () => query); + + const patch = $derived(detail.current.data?.patch ?? loadedPatch); + const activity = $derived(detail.current.data?.activity ?? loadedActivity); + // New reviews and comments show as they arrive: the diff keeps the first + // visible line in place when comments are added above it, so the user + // doesn't lose their place. + // A deleted patch has no revisions; keep the loaded ones until the view + // navigates away. + const revisions = $derived( + detail.current.data?.patch + ? detail.current.data.revisions + : loadedRevisions, + ); + + // Deleted elsewhere while shown, so there is nothing left to show. + $effect(() => { + if (detail.current.data?.patch === null) { + void router.push({ resource: "repo.patches", rid: repo.rid, status }); + } + }); const currentReview = $derived.by(() => { if (!review) return undefined; @@ -187,6 +212,9 @@ }); // svelte-ignore state_referenced_locally let selectedRevisionId: string = $state(revisions.slice(-1)[0].id); + // A revision pushed meanwhile doesn't replace the selected one: the + // revision picker and "Back to latest revision" show that there is a newer + // one. const selectedRevision: Revision = $derived( revisions.find(r => r.id === selectedRevisionId) ?? revisions.slice(-1)[0], ); @@ -498,21 +526,12 @@ } } - async function loadPatch(patchId: string = patch.id) { - [patch, revisions, activity] = await Promise.all([ - invoke("patch_by_id", { - rid: repo.rid, - id: patchId, - }), - invoke("revisions_by_patch", { - rid: repo.rid, - id: patchId, - }), - invoke[]>("activity_by_patch", { - rid: repo.rid, - id: patchId, - }), - ]); + // After the user's own changes, refetch and show them right away. + async function loadPatch() { + await queryClient.invalidateQueries({ + queryKey: query.queryKey, + refetchType: "all", + }); } // A draft review belongs to a single revision, mirroring the protocol's diff --git a/desktop/src/views/repo/Patches.svelte b/desktop/src/views/repo/Patches.svelte index 7a9fd211e..437bc0fdc 100644 --- a/desktop/src/views/repo/Patches.svelte +++ b/desktop/src/views/repo/Patches.svelte @@ -6,8 +6,11 @@ import type { RepoInfo } from "@bindings/repo/RepoInfo"; import { DEFAULT_TAKE } from "@app/views/repo/router"; + import { keys } from "@radicle-gui/core/keys"; + import { createQuery, onInvalidate } from "@radicle-gui/ui/lib/query.svelte"; import delay from "lodash/delay"; + import { repoInfo } from "@app/lib/cobQueries"; import { searchCobs } from "@app/lib/cobSearch"; import { debounced } from "@app/lib/debounced.svelte"; import { channel, invoke } from "@app/lib/invoke"; @@ -19,6 +22,7 @@ resetPatchCounts, updatePatchCounts, } from "@app/lib/patchCounts.svelte"; + import { queryClient } from "@app/lib/query"; import * as router from "@app/lib/router"; import type { SidebarData } from "@app/lib/router/definitions"; import { modifierKey } from "@app/lib/utils"; @@ -42,9 +46,11 @@ sidebarData: SidebarData; } - /* eslint-disable prefer-const */ - let { repo, patches, status, sidebarData }: Props = $props(); - /* eslint-enable prefer-const */ + const { repo: loadedRepo, patches, status, sidebarData }: Props = $props(); + + // Its counts change with every patch, so it follows the cache. + const repoQuery = createQuery(queryClient, () => repoInfo(loadedRepo.rid)); + const repo = $derived(repoQuery.current.data ?? loadedRepo); function listKey(filter: PatchStatus | undefined): string { return `repo.patches:${repo.rid}:${filter ?? "all"}`; @@ -79,8 +85,15 @@ $effect(() => { // Only record counts from settled, fresh data: while a history-restore // revalidation is in flight (loadingMore), the snapshot's length/more are - // stale and would flag a cache mismatch that isn't there. - if (list.more === false && !list.loadingMore) { + // stale and would flag a cache mismatch that isn't there. An update + // refreshes the list and the repo's counts separately, so one of them + // can briefly be ahead of the other. + if ( + list.more === false && + !list.loadingMore && + !list.refreshing && + !repoQuery.current.isFetching + ) { updatePatchCounts(list.items.length, project.meta.patches, status); } }); @@ -116,14 +129,17 @@ const contextMenu = createListContextMenu(() => list.items); async function refresh() { - // Re-fetch the repo too: the tab counts come from its project payload. - const [repoInfo] = await Promise.all([ - invoke("repo_by_id", { rid: repo.rid }), - list.revalidate(Math.max(list.items.length, DEFAULT_TAKE)), - ]); - repo = repoInfo; + await list.refresh(); } + // The paginated list keeps its own pages, so the cache only tells + // it when to refresh. + onInvalidate( + queryClient, + () => keys.patchList(repo.rid, status ?? "all"), + refresh, + ); + const searchResults = $derived( searchCobs(debouncedSearch.current, list.items), ); diff --git a/desktop/src/views/repo/router.ts b/desktop/src/views/repo/router.ts index 3795bba18..22423775e 100644 --- a/desktop/src/views/repo/router.ts +++ b/desktop/src/views/repo/router.ts @@ -21,13 +21,18 @@ import type { Readme } from "@bindings/repo/Readme"; import type { RepoInfo } from "@bindings/repo/RepoInfo"; import type { Tree } from "@bindings/source/Tree"; +import { keys } from "@radicle-gui/core/keys"; +import { markLoading } from "@radicle-gui/ui/lib/query.svelte"; + import type { BoardView } from "@app/lib/board"; import { loadView } from "@app/lib/boardView"; +import { issueDetail, load, patchDetail, repoInfo } from "@app/lib/cobQueries"; import { cachedGetCommitDiff, cachedGetDiffText, invoke, } from "@app/lib/invoke"; +import { queryClient } from "@app/lib/query"; import type { LoadedRoute, SidebarData } from "@app/lib/router/definitions"; import { loadSidebarData } from "@app/lib/router/definitions"; import { unreachable } from "@app/lib/utils"; @@ -286,9 +291,8 @@ export async function loadPatch( ): Promise { // Switching tab (view) or review on the same patch shouldn't refetch the // repo-wide data, so the sidebar and patch list are reused when we stay on - // the same patch. The patch itself, its revisions and its activity are - // always refetched: they change on every comment, review and edit, and a - // reused copy resurrects pre-mutation state when the tab changes. + // the same patch. The patch itself, its revisions and its activity load + // through the cache, which the view reads from. const reuse = previousLoaded?.resource === "repo.patch" && previousLoaded.params.repo.rid === route.rid && @@ -297,35 +301,20 @@ export async function loadPatch( ? previousLoaded.params : undefined; - const [[sidebarData, repo, patches], [patch, revisions, activity]] = + const [[sidebarData, repo, patches], { patch, revisions, activity }] = await Promise.all([ reuse ? ([reuse.sidebarData, reuse.repo, reuse.patches] as const) : Promise.all([ loadSidebarData(), - invoke("repo_by_id", { - rid: route.rid, - }), + load(repoInfo(route.rid)), invoke>("list_patches", { rid: route.rid, status: route.status, take: DEFAULT_TAKE, }), ] as const), - Promise.all([ - invoke("patch_by_id", { - rid: route.rid, - id: route.patch, - }), - invoke("revisions_by_patch", { - rid: route.rid, - id: route.patch, - }), - invoke[]>("activity_by_patch", { - rid: route.rid, - id: route.patch, - }), - ] as const), + load(patchDetail(route.rid, route.patch)), ]); // The patch may have been deleted (removed here, on another device, or a @@ -364,11 +353,10 @@ export async function loadPatch( export async function loadPatches( route: RepoPatchesRoute, ): Promise { + markLoading(queryClient, keys.patchList(route.rid, route.status ?? "all")); const [sidebarData, repo, patches] = await Promise.all([ loadSidebarData(), - invoke("repo_by_id", { - rid: route.rid, - }), + load(repoInfo(route.rid)), invoke>("list_patches", { rid: route.rid, status: route.status, @@ -403,9 +391,7 @@ async function loadSourceContext(route: { }): Promise { const [sidebarData, repo, commit] = await Promise.all([ loadSidebarData(), - invoke("repo_by_id", { - rid: route.rid, - }), + load(repoInfo(route.rid)), invoke("repo_commit", { rid: route.rid, peer: route.peer, @@ -480,9 +466,7 @@ export async function loadRepoCommit( ): Promise { const [sidebarData, repo, commit, diff, patch] = await Promise.all([ loadSidebarData(), - invoke("repo_by_id", { - rid: route.rid, - }), + load(repoInfo(route.rid)), invoke("repo_commit", { rid: route.rid, sha: route.commit, @@ -507,9 +491,7 @@ export async function loadIdentity( ): Promise { const [sidebarData, repo, identity] = await Promise.all([ loadSidebarData(), - invoke("repo_by_id", { - rid: route.rid, - }), + load(repoInfo(route.rid)), invoke("identity_by_repo", { rid: route.rid, }), @@ -523,26 +505,23 @@ export async function loadIdentity( export async function loadIssue( route: RepoIssueRoute, -): Promise { - const [sidebarData, repo, issue, activity, threads] = await Promise.all([ +): Promise { + const [sidebarData, repo, { issue, activity, threads }] = await Promise.all([ loadSidebarData(), - invoke("repo_by_id", { - rid: route.rid, - }), - invoke("issue_by_id", { - rid: route.rid, - id: route.issue, - }), - invoke[]>("activity_by_issue", { - rid: route.rid, - id: route.issue, - }), - invoke("comment_threads_by_issue_id", { - rid: route.rid, - id: route.issue, - }), + load(repoInfo(route.rid)), + load(issueDetail(route.rid, route.issue)), ]); + // The issue may have been deleted (here, on another device, or a stale + // link); fall back to the issue list instead of crashing. + if (!issue) { + return loadIssues({ + resource: "repo.issues", + rid: route.rid, + status: "open", + }); + } + return { resource: "repo.issue", params: { @@ -559,11 +538,10 @@ export async function loadIssue( export async function loadIssues( route: RepoIssuesRoute, ): Promise { + markLoading(queryClient, keys.issueList(route.rid, route.status)); const [sidebarData, repo, issues] = await Promise.all([ loadSidebarData(), - invoke("repo_by_id", { - rid: route.rid, - }), + load(repoInfo(route.rid)), invoke>("list_issues", { rid: route.rid, status: route.status, @@ -598,9 +576,7 @@ export async function loadReleases( const scope = route.scope ?? "trusted"; const [sidebarData, repo, releases, releaseCounts] = await Promise.all([ loadSidebarData(), - invoke("repo_by_id", { - rid: route.rid, - }), + load(repoInfo(route.rid)), listReleases(route.rid, scope, 0, RELEASES_PER_PAGE), invoke("release_counts", { rid: route.rid, @@ -628,9 +604,7 @@ export async function loadRelease( ): Promise { const [sidebarData, repo, release] = await Promise.all([ loadSidebarData(), - invoke("repo_by_id", { - rid: route.rid, - }), + load(repoInfo(route.rid)), invoke("release_by_id", { rid: route.rid, id: route.release, @@ -663,7 +637,7 @@ export async function loadBoard( const [sidebarData, repo, boards, issues, patches, links] = await Promise.all( [ loadSidebarData(), - invoke("repo_by_id", { rid: route.rid }), + load(repoInfo(route.rid)), invoke("list_boards", { rid: route.rid }), invoke>("list_issues", { rid: route.rid, diff --git a/desktop/tests/unit/paginatedList.svelte.test.ts b/desktop/tests/unit/paginatedList.svelte.test.ts index 27d3360fc..5de22b9d8 100644 --- a/desktop/tests/unit/paginatedList.svelte.test.ts +++ b/desktop/tests/unit/paginatedList.svelte.test.ts @@ -327,3 +327,89 @@ test("a fresh navigation ignores the snapshot", () => { expect(list.initialScrollOffset).toBeUndefined(); expect(fetchPage).not.toHaveBeenCalled(); }); + +test("a refresh started on a key change isn't undone by the list's reset", async () => { + let key = $state(`list-${++keyCount}`); + let current = $state(page(["a", "b"])); + let list!: ReturnType>; + cleanup = $effect.root(() => { + list = createPaginatedList({ + key: () => key, + page: () => current, + fetchPage, + pageSize: 2, + id: item => item, + }); + // As a view's `onInvalidate` does for an update during the new key's load. + let seen = key; + $effect.pre(() => { + if (key !== seen) { + seen = key; + void list.revalidate(); + } + }); + }); + flushSync(); + fetchPage.mockResolvedValueOnce(page(["fresh"], false)); + + key = `list-${++keyCount}`; + current = page(["stale"]); + flushSync(); + + await vi.waitFor(() => expect(list.items).toEqual(["fresh"])); +}); + +test("a refresh during a page load leaves the list able to load more", async () => { + const { list } = setup(); + const pageLoad = deferred(); + fetchPage.mockReturnValueOnce(pageLoad.promise); + const loading = list.loadMore(); + fetchPage.mockResolvedValueOnce(page(["new", "a", "b", "c"])); + + await list.refresh(); + pageLoad.resolve(page(["c", "d"])); + await loading; + + expect(list.items).toEqual(["new", "a", "b"]); + expect(list.loadingMore).toBe(false); + expect(list.more).toBe(true); +}); + +test("a page load waits for a refresh in flight", async () => { + const { list } = setup(); + const refreshed = deferred(); + fetchPage.mockReturnValueOnce(refreshed.promise); + const refreshing = list.refresh(); + fetchPage.mockResolvedValueOnce(page(["b", "c"], false)); + const loading = list.loadMore(); + + refreshed.resolve(page(["new", "a", "b"])); + await Promise.all([refreshing, loading]); + + expect(list.items).toEqual(["new", "a", "b", "c"]); + expect(fetchPage.mock.calls.map(([skip]) => skip)).toEqual([0, 3]); + expect(list.loadingMore).toBe(false); +}); + +test("a refresh keeps the list's end, so rows added at the top don't push it", async () => { + const { list } = setup(page(["a", "b"])); + fetchPage.mockResolvedValueOnce(page(["new", "a", "b", "c"])); + + await list.refresh(); + + expect(list.items).toEqual(["new", "a", "b"]); + expect(list.more).toBe(true); +}); + +test("says when it is refreshing", async () => { + const { list } = setup(); + const refreshed = deferred(); + fetchPage.mockReturnValueOnce(refreshed.promise); + + const refreshing = list.refresh(); + expect(list.refreshing).toBe(true); + refreshed.resolve(page(["a", "b"], false)); + await refreshing; + + expect(list.refreshing).toBe(false); +}); diff --git a/shared/core/src/keys.ts b/shared/core/src/keys.ts index b0bca289f..158386c8d 100644 --- a/shared/core/src/keys.ts +++ b/shared/core/src/keys.ts @@ -1,5 +1,6 @@ // Keys of the data that shared code reads, by domain identity. Every key of a // repository starts with `["repo", rid]`, so that prefix covers all of it. +// Data that spans repositories, such as notifications, has its own root. export type Key = readonly string[]; export const keys = { @@ -7,9 +8,15 @@ export const keys = { repoInfo: (rid: string) => ["repo", rid, "info"] as const, code: (rid: string) => ["repo", rid, "code"] as const, issues: (rid: string) => ["repo", rid, "issues"] as const, + // One status's list; `status` is the filter as the view names it. + issueList: (rid: string, status: string) => + ["repo", rid, "issues", status] as const, issue: (rid: string, id: string) => ["repo", rid, "issue", id] as const, patches: (rid: string) => ["repo", rid, "patches"] as const, + patchList: (rid: string, status: string) => + ["repo", rid, "patches", status] as const, patch: (rid: string, id: string) => ["repo", rid, "patch", id] as const, + notificationCount: () => ["notifications", "count"] as const, }; // Lists of CI jobs, which scanning every job COB of a repository builds.