Skip to content

Build your personal knowledge base with Trilium Notes

client/image compression tool: display progress while running as a cleanup operation

Adorian Doran16987fd76b63
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx
index 1c692ffcd3..936ecfb9f9 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx
@@ -37,9 +37,24 @@ const mocks = vi.hoisted(() => ({
weighed: [] as number[],
save: vi.fn(async () => {}),
get: vi.fn(),
- post: vi.fn(async (url: string, _body?: object) => (
- url === "database/vacuum-database" ? { sizeBefore: VACUUM_BEFORE, sizeAfter: VACUUM_AFTER } : undefined
- )),
+ /** Whoever is listening to the websocket, which for the length of a run is the run itself. */
+ listeners: [] as ((message: unknown) => void)[],
+ /** What the server reports over that socket while a compression request is still open. */
+ progress: [] as { progressCount: number; totalCount?: number }[],
+ post: vi.fn(async (url: string, body?: object) => {
+ if (url === "database/vacuum-database") {
+ return { sizeBefore: VACUUM_BEFORE, sizeAfter: VACUUM_AFTER };
+ }
+
+ if (url === "notes/root/compress-images") {
+ const { taskId } = (body ?? {}) as { taskId?: string };
+
+ mocks.progress.forEach((report) => mocks.listeners.forEach(
+ (listener) => listener({ type: "taskProgressCount", taskId, ...report })));
+ }
+
+ return undefined;
+ }),
/** Takes the confirmation element, which one test renders to read what it says. */
confirm: vi.fn(async (_message?: unknown) => true),
showMessage: vi.fn<(message: string, timeout?: number) => void>(),
@@ -98,6 +113,30 @@ vi.mock("../../../../../services/server", () => {
};
});
+// i18next is never initialised for these tests, and answers `undefined` to everything until it is —
+// which would make every comparison against a t() call below true of any two messages at all. Keys
+// and their interpolations stand in for the sentences, so that a wrong one reads as wrong.
+vi.mock("../../../../../services/i18n", () => ({
+ t: (key: string, params?: Record<string, unknown>) => (params ? `${key} ${JSON.stringify(params)}` : key),
+ translationsInitializedPromise: Promise.resolve(),
+ initLocale: async () => {},
+ getAvailableLocales: () => [],
+ getLocaleById: () => null,
+ getCurrentLanguage: () => "en"
+}));
+
+// The compression step is followed over the websocket rather than answered by the request, so the
+// socket is where its counting has to be driven from.
+vi.mock("../../../../../services/ws", () => {
+ const subscribeToMessages = (listener: (message: unknown) => void) => void mocks.listeners.push(listener);
+ const unsubscribeToMessage = (listener: (message: unknown) => void) =>
+ void mocks.listeners.splice(mocks.listeners.indexOf(listener), 1);
+
+ // Named and default both: the run reaches for the named exports, while modules the dialog pulls
+ // in on the way past subscribe through the default object.
+ return { subscribeToMessages, unsubscribeToMessage, default: { subscribeToMessages, unsubscribeToMessage } };
+});
+
vi.mock("../../../../../services/dialog", () => ({ default: { confirm: mocks.confirm } }));
vi.mock("../../../../../services/toast", () => ({
default: {
@@ -189,6 +228,8 @@ async function click(button: HTMLButtonElement | undefined) {
beforeEach(() => {
mocks.storedOption = "{}";
mocks.weighed = [ MEASURED_BEFORE, MEASURED_AFTER ];
+ mocks.listeners.length = 0;
+ mocks.progress.length = 0;
mocks.getInt.mockReturnValue(-1);
mocks.confirm.mockResolvedValue(true);
vi.clearAllMocks();
@@ -230,9 +271,12 @@ describe("showCleanupDialog", () => {
mocks.storedOption = JSON.stringify({ revisionSnapshots: true, snapshotsToKeep: 2 });
await openDialog();
- // The whole is the history erased outright plus the rest; the offer, only what is picked.
+ // The whole is the history erased outright plus the rest, and the pages already free inside
+ // the file along with them — everything a run could hand back. The offer is only what is
+ // picked, which here is none of it.
expect(textOf(".cleanup-chart-total")).toBe(
- t("space_usage.cleanup_amount_of", { total: formatSize(REVISIONS_ALL + DELETED + UNUSED) }) ?? "");
+ t("space_usage.cleanup_amount_of",
+ { total: formatSize(REVISIONS_ALL + DELETED + UNUSED + FREE_PAGES) }) ?? "");
expect(textOf(".cleanup-chart-amount")).toBe(formatSize(REVISIONS_TRIMMED));
await toggle(rows()[0]);
@@ -357,6 +401,23 @@ describe("showCleanupDialog", () => {
expect(mocks.closePersistent).toHaveBeenCalledWith(CLEANUP_TOAST_ID);
});
+ it("counts the images off in the toast, once the compression run says how many there are", async () => {
+ mocks.progress = [ { progressCount: 1 }, { progressCount: 197, totalCount: 867 } ];
+ const { closed } = await openDialog();
+
+ await toggle(document.body.querySelector<HTMLElement>(".cleanup-item-compress") ?? undefined);
+ await click(cleanButton());
+ await closed;
+
+ expect(mocks.showPersistent.mock.calls.map(([ options ]) => options.message)).toEqual([
+ // Named while the request is being made, there being nothing to count yet — and again
+ // for a first report that carried no total, which is the same nothing to count against.
+ t("space_usage.compress_running"),
+ t("space_usage.compress_running"),
+ t("space_usage.compress_running_progress", { done: 197, total: 867 })
+ ]);
+ });
+
it("reports the file's own reduction as the whole of what a compacting run reclaimed", async () => {
mocks.storedOption = JSON.stringify({ unusedAttachments: true });
const { closed } = await openDialog();
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx
index 0df3ff34b2..93910953db 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx
@@ -28,6 +28,7 @@ import { useFetch } from "../../../../react/use_fetch";
import {
CLEANUP_ITEMS,
type CleanupPhase,
+ type CleanupProgress,
type CleanupToolOptions,
computeCleanupSizes,
hasWorkToDo,
@@ -376,24 +377,36 @@ export const CLEANUP_TOAST_ID = "content-manager-cleanup";
const CLEANUP_DONE_TIMEOUT_MS = 15000;
/**
- * The app's in-progress toast, the same one printing raises: a spinning icon rather than a bar,
- * since none of this can say how far along it is. Compressing and compacting each name themselves,
- * being the steps that can hold the server for minutes with nothing at all to show meanwhile.
+ * The app's in-progress toast, the same one printing raises: a spinning icon rather than a bar.
+ * Compressing and compacting each name themselves, being the steps that can hold the server for
+ * minutes with nothing at all to show meanwhile.
*
- * Raised again per phase rather than replaced — the toast service updates the one already carrying
+ * Raised again per report rather than replaced — the toast service updates the one already carrying
* this id, so the message changes in place instead of stacking a second toast beside the first.
*/
-function showCleanupProgress(phase: CleanupPhase) {
+function showCleanupProgress(phase: CleanupPhase, progress?: CleanupProgress) {
toast.showPersistent({
id: CLEANUP_TOAST_ID,
icon: "bx bx-loader-circle bx-spin",
- message: t(CLEANUP_PHASE_MESSAGES[phase]),
+ message: phaseMessage(phase, progress),
// Nothing here to cancel: the server carries on whatever the client does, so a close button
// would read as a stop that stops nothing.
dismissible: false
});
}
+/**
+ * A phase counts itself off where it can, and merely names itself where it cannot.
+ *
+ * Recompressing is the only one that can, and only once its first report has arrived: the total
+ * comes from the server along with the count, so until then this reads as the other phases do.
+ */
+function phaseMessage(phase: CleanupPhase, progress?: CleanupProgress): string {
+ return progress?.total
+ ? t("space_usage.compress_running_progress", { done: progress.done, total: progress.total })
+ : t(CLEANUP_PHASE_MESSAGES[phase]);
+}
+
/**
* Compressing borrows the image tool's own wording rather than keeping a second copy of it: the
* step is that tool, run from here, and the two would only ever be corrected together.
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts
index 5f99462890..96eece0d1b 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts
@@ -5,11 +5,22 @@ const mocks = vi.hoisted(() => ({
getInt: vi.fn<(name: string) => number | null>(() => -1),
/** Reads the `revisionIgnoreNamedSnapshots` option, which the named-revisions field follows. */
is: vi.fn<(name: string) => boolean>(() => true),
- post: vi.fn(async (url: string, _body?: object) => {
+ /** Whoever is listening to the websocket, which for the length of a run is the run itself. */
+ listeners: [] as ((message: unknown) => void)[],
+ /** What the server reports over that socket while a compression request is still open. */
+ progress: [] as { progressCount: number; totalCount?: number }[],
+ post: vi.fn(async (url: string, body?: object) => {
if (url === "database/vacuum-database") return { sizeBefore: 9000, sizeAfter: 2000 };
// A saving far larger than any reading here, so a test can prove it is never added on top:
// the compression step runs between the two readings and is already counted in them.
- if (url === "notes/root/compress-images") return { savedSize: 999999 };
+ if (url === "notes/root/compress-images") {
+ const { taskId } = (body ?? {}) as { taskId?: string };
+
+ mocks.progress.forEach((report) => mocks.listeners.forEach(
+ (listener) => listener({ type: "taskProgressCount", taskId, ...report })));
+
+ return { savedSize: 999999 };
+ }
return undefined;
}),
/** Occupied bytes, read once before the erasures and once after; shifted per test. */
@@ -36,8 +47,18 @@ vi.mock("../../../../../services/server", () => ({
}
}));
+// The compression step is followed over the websocket rather than answered by the request, so the
+// socket is where its counting has to be driven from.
+vi.mock("../../../../../services/ws", () => ({
+ subscribeToMessages: (listener: (message: unknown) => void) => void mocks.listeners.push(listener),
+ unsubscribeToMessage: (listener: (message: unknown) => void) =>
+ void mocks.listeners.splice(mocks.listeners.indexOf(listener), 1)
+}));
+
import type { ImageCompressionToolOptions } from "../../../../dialogs/image_compression/image_compression_options";
import {
+ type CleanupPhase,
+ type CleanupProgress,
type CleanupToolOptions,
computeCleanupSizes,
hasWorkToDo,
@@ -80,10 +101,21 @@ const ALL_PICKED: CleanupToolOptions = {
compactDatabase: false
};
+/** Recompressing on its own, so the phases a run reports are that step's and nothing else's. */
+const ONLY_COMPRESSING: CleanupToolOptions = {
+ ...ALL_PICKED,
+ deletedEntities: false,
+ unusedAttachments: false,
+ revisionSnapshots: false,
+ compressImages: true
+};
+
beforeEach(() => {
mocks.getInt.mockReturnValue(-1);
mocks.is.mockReturnValue(true);
mocks.occupied = [ 5000, 3000 ];
+ mocks.listeners.length = 0;
+ mocks.progress.length = 0;
mocks.post.mockClear();
mocks.get.mockClear();
});
@@ -266,6 +298,9 @@ describe("runCleanup", () => {
]);
// The whole tree, and none of the tool's own scope switch — a cleanup has no scope to choose.
expect(mocks.post.mock.calls[3][1]).toEqual({
+ // Named, which is the whole of what it takes to be counted: the server reports each
+ // image against a task, and there is a task only because the request quoted one.
+ taskId: expect.any(String),
resize: true,
maxWidthHeight: 1920,
jpegHandling: "compress",
@@ -276,6 +311,40 @@ describe("runCleanup", () => {
});
});
+ it("counts the images off as the run reports them, against a total it supplies itself", async () => {
+ const reported: [ CleanupPhase, CleanupProgress | undefined ][] = [];
+
+ mocks.progress = [ { progressCount: 1, totalCount: 867 }, { progressCount: 197, totalCount: 867 } ];
+
+ await runCleanup({ ...ONLY_COMPRESSING }, (phase, progress) => reported.push([ phase, progress ]));
+
+ // The phase announces itself before the request is made — nothing can be counted yet — and
+ // is then re-announced with each report. No inventory is read for the total: the run knows
+ // how many images it collected before it touches the first, and says so as it goes.
+ expect(reported).toEqual([
+ [ "compressing", undefined ],
+ [ "compressing", { done: 1, total: 867 } ],
+ [ "compressing", { done: 197, total: 867 } ]
+ ]);
+ });
+
+ it("hears only its own run, and stops listening once that run is over", async () => {
+ const reported: CleanupProgress[] = [];
+
+ mocks.progress = [ { progressCount: 5, totalCount: 40 } ];
+
+ await runCleanup({ ...ONLY_COMPRESSING }, (_phase, progress) => {
+ if (progress) {
+ reported.push(progress);
+ }
+ });
+
+ expect(reported).toEqual([ { done: 5, total: 40 } ]);
+ // Subscribed for the length of the request rather than the length of the session: a second
+ // run's reports must not still be counted against a toast this one has taken down.
+ expect(mocks.listeners).toEqual([]);
+ });
+
it("counts what compressing freed once, through the readings rather than the endpoint", async () => {
mocks.occupied = [ 5000, 1200 ];
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts
index c1a474d18c..bd228161c5 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts
@@ -1,6 +1,5 @@
import type {
CompactionEstimateResponse,
- ImageCompressionResponse,
SpaceUsageNoteResponse,
SpaceUsageOverviewResponse,
VacuumDatabaseResponse
@@ -8,6 +7,7 @@ import type {
import optionService from "../../../../../services/options";
import server from "../../../../../services/server";
+import { newCompressionTaskId, runImageCompression } from "../../../../dialogs/image_compression/image_compression_operation";
import {
CONSERVATIVE_IMAGE_COMPRESSION_DEFAULTS,
type ImageCompressionToolOptions,
@@ -30,6 +30,18 @@ export type CleanupItemId = (typeof CLEANUP_ITEMS)[number]["id"];
*/
export type CleanupPhase = "erasing" | "compressing" | "compacting";
+/**
+ * How far a phase has got, for the one phase that can say.
+ *
+ * Erasing and rebuilding are each a single request the server answers when it is finished; only
+ * recompressing works through a list it knows the length of, and reports itself against it.
+ */
+export interface CleanupProgress {
+ done: number;
+ /** Absent until the run has said how many there are, which its first report does. */
+ total?: number;
+}
+
/**
* What the cleanup tool is set to erase. Persisted as JSON in the `cleanupToolOptions` option — all
@@ -206,7 +218,7 @@ export function computeCleanupSizes(
*/
export async function runCleanup(
options: CleanupToolOptions,
- onPhase: (phase: CleanupPhase) => void = () => {}
+ onPhase: (phase: CleanupPhase, progress?: CleanupProgress) => void = () => {}
): Promise<number> {
const erasing = options.revisionSnapshots || options.unusedAttachments || options.deletedEntities;
@@ -235,7 +247,8 @@ export async function runCleanup(
if (options.compressImages) {
onPhase("compressing");
- await compressAllImages(options.imageCompression);
+ await compressAllImages(options.imageCompression,
+ (done, total) => onPhase("compressing", { done, total }));
}
let compaction: VacuumDatabaseResponse | undefined;
@@ -273,20 +286,23 @@ export async function runCleanup(
* readings show is what the database actually handed back, which is smaller whenever a revision
* still points at an original. Only the second is a claim about space, and space is what this tool
* is answering for.
+ *
+ * Run through the image tool's own runner rather than posted from here, which is what names the run
+ * and so what lets it be counted: the server reports each image against a task, and a task exists
+ * only because the request quoted one. The count itself costs nothing to obtain — the run knows how
+ * many images it collected before it touches the first, and says so with its first report.
*/
-async function compressAllImages(options: ImageCompressionToolOptions): Promise<void> {
- await server.postWithTimeout<ImageCompressionResponse>(
- "notes/root/compress-images", CLEANUP_TIMEOUT_MS, {
- resize: options.resize,
- maxWidthHeight: options.maxWidthHeight,
- jpegHandling: options.jpegHandling,
- pngHandling: options.pngHandling,
- quality: options.quality,
- conversionQuality: options.conversionQuality,
- // Always the whole tree: a cleanup is a database-wide operation, and the root note on
- // its own holds no images at all.
- recursive: true
- });
+async function compressAllImages(
+ options: ImageCompressionToolOptions,
+ onProgress: (done: number, total: number | undefined) => void
+): Promise<void> {
+ await runImageCompression(
+ { type: "note", noteId: "root" },
+ // Always the whole tree: a cleanup is a database-wide operation, and the root note on its
+ // own holds no images at all.
+ { ...options, processChildNotes: true },
+ newCompressionTaskId(),
+ onProgress);
}
/**