Skip to content

Build your personal knowledge base with Trilium Notes

feat(sync): show pull progress on the sync button

Elian Doran17d6b0cad849
diff --git a/apps/client/src/widgets/launch_bar/SyncStatus.css b/apps/client/src/widgets/launch_bar/SyncStatus.css
index dc9795e6aa..986bff5832 100644
--- a/apps/client/src/widgets/launch_bar/SyncStatus.css
+++ b/apps/client/src/widgets/launch_bar/SyncStatus.css
@@ -23,4 +23,29 @@
.sync-status-icon:not(.sync-status-in-progress):hover {
background-color: var(--hover-item-background-color);
cursor: pointer;
-}
\ No newline at end of file
+}
+
+.sync-status-widget {
+ position: relative;
+ overflow: hidden;
+}
+
+.sync-status-widget .sync-status-progress {
+ position: absolute;
+ bottom: 2px;
+ inset-inline: 7px;
+ border-radius: 6px;
+ overflow: hidden;
+ height: 3px;
+ background-color: var(--hover-item-background-color);
+ pointer-events: none;
+
+ &::after {
+ content: "";
+ display: block;
+ width: var(--sync-progress);
+ height: 100%;
+ background-color: var(--main-text-color);
+ transition: width 200ms ease-out;
+ }
+}
diff --git a/apps/client/src/widgets/launch_bar/SyncStatus.spec.tsx b/apps/client/src/widgets/launch_bar/SyncStatus.spec.tsx
index 955dc77438..0c1b4420df 100644
--- a/apps/client/src/widgets/launch_bar/SyncStatus.spec.tsx
+++ b/apps/client/src/widgets/launch_bar/SyncStatus.spec.tsx
@@ -137,4 +137,30 @@ describe("SyncStatus", () => {
expect(icon()).toBeNull();
}
});
+
+ it("fills a progress bar while pulling, and drops it once the pull is over", () => {
+ mount();
+ const bar = () => container.querySelector<HTMLElement>(".sync-status-progress");
+
+ act(() => { mocks.onMessage?.({ type: "sync-pull-in-progress", lastSyncedPush: 0 }); });
+ expect(bar()).toBeNull();
+
+ act(() => {
+ mocks.onMessage?.({ type: "sync-pull-in-progress", lastSyncedPush: 0, progress: { pulled: 25, total: 100 } });
+ });
+ const element = bar();
+ expect(element).not.toBeNull();
+ expect(element?.getAttribute("aria-valuenow")).toBe("25");
+ expect(element?.style.getPropertyValue("--sync-progress")).toBe("25%");
+
+ act(() => { mocks.onMessage?.({ type: "sync-push-in-progress", lastSyncedPush: 0 }); });
+ expect(bar()).toBeNull();
+
+ act(() => {
+ mocks.onMessage?.({ type: "sync-pull-in-progress", lastSyncedPush: 0, progress: { pulled: 5, total: 10 } });
+ });
+ expect(bar()).not.toBeNull();
+ act(() => { mocks.onMessage?.({ type: "sync-finished", lastSyncedPush: 0 }); });
+ expect(bar()).toBeNull();
+ });
});
diff --git a/apps/client/src/widgets/launch_bar/SyncStatus.tsx b/apps/client/src/widgets/launch_bar/SyncStatus.tsx
index b4b2c2f2c6..a93a8a7b5d 100644
--- a/apps/client/src/widgets/launch_bar/SyncStatus.tsx
+++ b/apps/client/src/widgets/launch_bar/SyncStatus.tsx
@@ -1,6 +1,6 @@
import "./SyncStatus.css";
-import { WebSocketMessage } from "@triliumnext/commons";
+import { SyncPullProgress, WebSocketMessage } from "@triliumnext/commons";
import clsx from "clsx";
import { useEffect, useRef, useState } from "preact/hooks";
@@ -51,7 +51,7 @@ const STATE_MAPPINGS: Record<SyncState, StateMapping> = {
};
export default function SyncStatus({ launcherNote }: LauncherNoteProps) {
- const syncState = useSyncStatus();
+ const { syncState, pullProgress } = useSyncStatus();
const { title, icon, hasChanges } = STATE_MAPPINGS[syncState];
const spanRef = useRef<HTMLSpanElement>(null);
const [ storedSyncServerHost ] = useTriliumOption("syncServerHost");
@@ -90,12 +90,29 @@ export default function SyncStatus({ launcherNote }: LauncherNoteProps) {
)}
</span>
</div>
+ {pullProgress && <SyncPullProgressBar {...pullProgress} />}
</div>
);
}
+function SyncPullProgressBar({ pulled, total }: SyncPullProgress) {
+ const percent = Math.min(100, Math.round(pulled / total * 100));
+
+ return (
+ <div
+ class="sync-status-progress"
+ role="progressbar"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={percent}
+ style={{ "--sync-progress": `${percent}%` }}
+ />
+ );
+}
+
function useSyncStatus() {
const [ syncState, setSyncState ] = useState<SyncState>("unknown");
+ const [ pullProgress, setPullProgress ] = useState<SyncPullProgress>();
useEffect(() => {
let lastSyncedPush: number;
@@ -113,14 +130,22 @@ function useSyncStatus() {
switch (message.type) {
case "sync-pull-in-progress":
+ setSyncState("in-progress");
+ if (message.progress && message.progress.total > 0) {
+ setPullProgress(message.progress);
+ }
+ break;
case "sync-push-in-progress":
setSyncState("in-progress");
+ setPullProgress(undefined);
break;
case "sync-finished":
setSyncState(allChangesPushed ? "connected-no-changes" : "connected-with-changes");
+ setPullProgress(undefined);
break;
case "sync-failed":
setSyncState(allChangesPushed ? "disconnected-no-changes" : "disconnected-with-changes");
+ setPullProgress(undefined);
break;
case "frontend-update":
lastSyncedPush = message.data.lastSyncedPush;
@@ -132,5 +157,5 @@ function useSyncStatus() {
return () => unsubscribeToMessage(onMessage);
}, []);
- return syncState;
+ return { syncState, pullProgress };
}
diff --git a/packages/commons/src/lib/ws_api.ts b/packages/commons/src/lib/ws_api.ts
index df12d5c2e1..c93f1993ee 100644
--- a/packages/commons/src/lib/ws_api.ts
+++ b/packages/commons/src/lib/ws_api.ts
@@ -114,6 +114,11 @@ export interface OpenedFileUpdateStatus {
filePath: string;
}
+export interface SyncPullProgress {
+ pulled: number;
+ total: number;
+}
+
type AllTaskDefinitions =
| TaskDefinition<"empty">
| TaskDefinition<"deleteNotes">
@@ -166,8 +171,13 @@ export type WebSocketMessage = AllTaskDefinitions | {
type: "reload-frontend";
reason: string;
} | {
- type: "sync-pull-in-progress" | "sync-push-in-progress" | "sync-finished" | "sync-failed";
+ type: "sync-push-in-progress" | "sync-finished" | "sync-failed";
+ lastSyncedPush: number;
+} | {
+ type: "sync-pull-in-progress";
lastSyncedPush: number;
+ /** How many of the changes known to this sync run have been applied so far. */
+ progress?: SyncPullProgress;
} | {
/**
* Syncing stopped because the content hashes of these sectors kept differing from the sync
diff --git a/packages/trilium-core/src/services/sync.spec.ts b/packages/trilium-core/src/services/sync.spec.ts
index a59708bd04..31215baa7b 100644
--- a/packages/trilium-core/src/services/sync.spec.ts
+++ b/packages/trilium-core/src/services/sync.spec.ts
@@ -152,6 +152,31 @@ describe("sync service", () => {
expect(events.indexOf("fetch:2")).toBeGreaterThan(events.indexOf("apply"));
});
+ it("broadcasts pull progress after each applied batch", async () => {
+ const prevInitialized = options.getOptionOrNull("initialized");
+ cls.init(() => options.setOption("initialized", "true"));
+ const bigChange = { entityChange: { entityName: "notes", entityId: "pp1" }, entity: { content: "x".repeat(33 * 1024 * 1024) } };
+ const smallChange = { entityChange: { entityName: "notes", entityId: "pp2" }, entity: { content: "y" } };
+ config.changed = [
+ { entityChanges: [bigChange], lastEntityChangeId: 1, outstandingPullCount: 1 },
+ { entityChanges: [smallChange], lastEntityChangeId: 2, outstandingPullCount: 0 },
+ { entityChanges: [], lastEntityChangeId: 2, outstandingPullCount: 0 }
+ ];
+ vi.spyOn(syncUpdateService, "updateEntities").mockImplementation(() => {});
+ const pullSpy = vi.spyOn(ws, "syncPullInProgress");
+
+ try {
+ await expect(runSync()).resolves.toEqual({ success: true });
+ } finally {
+ cls.init(() => options.setOption("initialized", prevInitialized ?? "true"));
+ }
+
+ expect(pullSpy.mock.calls).toEqual([
+ [ { pulled: 1, total: 2 } ],
+ [ { pulled: 2, total: 2 } ]
+ ]);
+ });
+
it("marks the database as initialized once a sync converges", async () => {
// An initial sync-from-server interrupted by a crash resumes via sync/now or the sync
// timer — NOT via setup.triggerSync(), which is the only other place that sets the flag.
diff --git a/packages/trilium-core/src/services/sync.ts b/packages/trilium-core/src/services/sync.ts
index 00ed4140f4..ebcbdaf99e 100644
--- a/packages/trilium-core/src/services/sync.ts
+++ b/packages/trilium-core/src/services/sync.ts
@@ -406,6 +406,13 @@ async function pullChanges(syncContext: SyncContext) {
});
if (batch.length > 0) {
+ if (totalPullCount) {
+ ws.syncPullInProgress({
+ pulled: Math.max(0, totalPullCount - outstandingPullCount),
+ total: totalPullCount
+ });
+ }
+
log.info(
`Sync: pulled ${batch.length} chunk(s) (${batchChanges} changes, ~${Math.round(batchBytes / 1_048_576)} MB) in ${applyStart - fetchStart}ms and applied them in ${Date.now() - applyStart}ms, ${outstandingPullCount} outstanding pulls`
);
diff --git a/packages/trilium-core/src/services/ws.spec.ts b/packages/trilium-core/src/services/ws.spec.ts
index 6f74fe8aaa..e7fcddfddb 100644
--- a/packages/trilium-core/src/services/ws.spec.ts
+++ b/packages/trilium-core/src/services/ws.spec.ts
@@ -172,6 +172,11 @@ describe("ws service (real DB)", () => {
]));
const pull = sentAll.find((m) => m.type === "sync-pull-in-progress");
expect(pull).toMatchObject({ lastSyncedPush: 42 });
+
+ ws.syncPullInProgress({ pulled: 3, total: 10 });
+ expect(sentAll.at(-1)).toEqual({
+ type: "sync-pull-in-progress", lastSyncedPush: 42, progress: { pulled: 3, total: 10 }
+ });
expect(sentAll.find((m) => m.type === "sync-hash-check-failed")).toMatchObject({ sectors: ["blobs/9"] });
});
diff --git a/packages/trilium-core/src/services/ws.ts b/packages/trilium-core/src/services/ws.ts
index ae54b2242f..ee09337063 100644
--- a/packages/trilium-core/src/services/ws.ts
+++ b/packages/trilium-core/src/services/ws.ts
@@ -1,4 +1,4 @@
-import { type EntityChange, WebSocketMessage } from "@triliumnext/commons";
+import { type EntityChange, type SyncPullProgress, WebSocketMessage } from "@triliumnext/commons";
import becca from "../becca/becca.js";
import * as cls from "./context.js";
@@ -184,8 +184,8 @@ function sendTransactionEntityChangesToAllClients() {
}
}
-function syncPullInProgress() {
- sendMessageToAllClients({ type: "sync-pull-in-progress", lastSyncedPush });
+function syncPullInProgress(progress?: SyncPullProgress) {
+ sendMessageToAllClients({ type: "sync-pull-in-progress", lastSyncedPush, ...(progress && { progress }) });
}
function syncPushInProgress() {